首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建线程安全的GetEventHandler()?

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

Stack Overflow用户
提问于 2016-03-28 15:12:36
回答 1查看 79关注 0票数 1
代码语言:javascript
复制
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
    }
}

我有以下例外:

代码语言:javascript
复制
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; });

我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-28 16:05:13

根据您的评论,您说您是从后台线程调用JobDataDuplicatorForm(IJobDataDuplicatorEngine engine)的。

您的类是一个Form,任何windows控件(包括表单)都必须首先在UI线程或诸如InvokeInvokeRequired中断之类的东西上创建。无论调用什么代码,JobDataDuplicatorForm的构造函数都必须从UI线程执行该调用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36265163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档