【问题标题】:Multithreading, return value on Control.Invoke()多线程,Control.Invoke() 上的返回值
【发布时间】:2013-10-22 02:57:54
【问题描述】:

我在一个 win 应用程序上使用多线程

System.Threading.ThreadPool.QueueUserWorkItem(delegate{}, null);

问题是我的方法需要在主线程(DialogeResult 对象)上有一个返回值,而使用this.Invoke() 我无法从主线程获取值。方法代码如下:

public static DialogResult Show(IWin32Window owner, PSSettings.Settings settings, string title, string caption, MessageBoxButtons buttons)
    {

        return (DialogResult)((Form)owner).Invoke((Action)(() =>
        {
            PSMessageBox mb = new PSMessageBox();
            mb._settings = settings;

            mb.lblTitle.Text = title;
            mb.lblCaption.Text = caption;
            mb.Buttons = buttons;

            return mb.ShowDialog();
            mb.ShowDialog(owner);
        }));
    }

谁能告诉我如何使用任何类型的委托从调用方法中获取返回值?

【问题讨论】:

  • 通常QueueUserWorkItem 不应打开模态表单。您应该使用 ThreadPool 进行简短的后台工作,并且您确定可以将 IWin32Window 转换为 Form

标签: c# windows multithreading winforms delegates


【解决方案1】:

你可以这样做:

public static DialogResult Show(IWin32Window owner, PSSettings.Settings settings, string title, string caption, MessageBoxButtons buttons)
{
    DialogResult result;

    ((Form)owner).Invoke((Action)(() =>
    {
        PSMessageBox mb = new PSMessageBox();
        mb._settings = settings;

        mb.lblTitle.Text = title;
        mb.lblCaption.Text = caption;
        mb.Buttons = buttons;

        result = mb.ShowDialog(owner);
    }));

    return result;
}

但请记住,当您的对话框是 openend 时,您的线程会被阻塞。

【讨论】:

    【解决方案2】:
            DialogResult res;
            ((Form)owner).Invoke((Action)(() =>
            {
                PSMessageBox mb = new PSMessageBox();
                mb._settings = settings;
    
                mb.lblTitle.Text = title;
                mb.lblCaption.Text = caption;
                mb.Buttons = buttons;
    
    
                res = mb.ShowDialog(owner);
            }));
            //user res
    

    【讨论】:

      【解决方案3】:

      Action<*> 代表不返回任何内容。
      您需要通用的 Func<*> 代表,它可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-23
        • 1970-01-01
        • 1970-01-01
        • 2013-11-06
        • 2012-02-27
        相关资源
        最近更新 更多