-1

我在一个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);
        }));
    }

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

4

3 回答 3

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

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

于 2013-10-14T14:04:13.610 回答
0

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

于 2013-10-14T14:04:13.343 回答
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
于 2013-10-14T14:04:16.227 回答