如何创建线程安全的GetEventHandler()?

时间:2016-03-28 15:12:37

标签: c# multithreading

public partial class JobDataDuplicatorForm : Form
{
    public JobDataDuplicatorForm(IJobDataDuplicatorEngine engine)
    {
        _engine.CopyStartedEvent += GetEventHandler(OnCopyStarted);
        _engine.CopyEndedEvent += GetEventHandler(OnCopyEnded);
        ...
    }

    private static EventHandler GetEventHandler(Action action)
    {
        return (sender, args) => action();
    }

    private void OnCopyStarted()
    {
        copyStatus.Text = "Copy progress: ";
        generateButton.Enabled = false; // Cross-thread operation not valid
    }
}

我有以下例外:

Additional information: Cross-thread operation not valid: Control 
'generateButton' accessed from a thread other than the thread it was created on.

我是否可以通过更改GetEventHandler()来修复异常,而不是将每个按钮包装在不同的位置,例如

Invoke((MethodInvoker)delegate { generateButton.Enabled = false; });

我该怎么做?

1 个答案:

答案 0 :(得分:2)

根据您的评论,您说您从后台主题调用JobDataDuplicatorForm(IJobDataDuplicatorEngine engine)

您的类是Form,任何Windows控件(包括Form)都必须首先在UI线程上创建,或者InvokeInvokeRequired之类的内容。无论调用什么代码,JobDataDuplicatorForm的构造函数都必须从UI线程进行调用。