多线程,Control.Invoke()的返回值

时间:2013-10-14 14:00:36

标签: c# windows multithreading winforms delegates

我在使用

的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);
        }));
    }

有人能告诉我如何使用任何类型的委托从invoke方法获取返回值吗?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

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;
}

但请记住,当你的对话框开始时,你的线程被阻止了。

答案 1 :(得分:0)

Action<*>代表不返回任何内容 你需要通用的Func<*>代表。

答案 2 :(得分:0)

        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