繁体   English   中英

从单独的静态类在其线程的上下文中调用控件的方法

[英]Invoke method of the control in context of its thread from separate static class

我有一个表格和一些控制:

public class Tester : Form
{
    public Label Demo;

    public Label GetDemo()
    {
        return Demo.Text;
    }
}

我也有一些静态类:

public static bool Delay(Func<bool> condition)
{
    bool result = false;
    AutoResetEvent e = new AutoResetEvent(false);

    Timer t = new Timer(delegate {
        if (result = condition()) e.Set(); // wait until control property has needed value
    }, e, 0, 1000);

    e.WaitOne();
    t.Dispose();

    return result;
}

控件有时会创建新线程并调用我们的静态方法:

ThreadPool.QueueUserWorkItem(delegate {
    if (Delay(() => GetDemo() == "X")) MessageBox.Show("X");
}, null);

当然,这将导致异常,因为GetDemo将被传递给Delay并将作为委托在新线程中调用。

当然,可以通过使用Invoke调用我们的静态方法来解决它:

ThreadPool.QueueUserWorkItem(delegate {
    Invoke((MethodInvoker) delegate {
        if (Delay(() => GetDemo() == "X")) MessageBox.Show("OK");
    }
}, null);

不幸的是,我不允许更改Delay的调用,我只能更改其实现。

题 :

1)在静态方法Delay中需要更改什么,以便condition()可以在其本机线程中无例外地执行GetDemo?

2)是否可以在Delay内部做这样的事情?

SynchronizationContext.Dispatcher((Action) delegate {  
    if (condition()) e.Set();
});

此解决方案假定您的代码中还有其他地方可以接收UI线程上的更早调用,以保存UI SynchronizationContext的副本。 事实并非如此,在这种情况下,我建议的解决方案将无法工作。

// Assign this using SynchronizationContext.Current from a call made on the UI thread.
private static SynchronizationContext uiSynchronizationContext;

public static bool Delay(Func<bool> condition)
{
    bool result = false;
    AutoResetEvent e = new AutoResetEvent(false);

    Timer t = new Timer(delegate 
    {
        uiSynchronizationContext.Send(s => result = condition(), null);

        if (result)
            e.Set(); // wait until control property has needed value
    }, e, 0, 1000);

    e.WaitOne();
    t.Dispose();

    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM