通过在线程库中处理来消除对 Invoke() 的需求 [英] Remove need for Invoke() by handling within threaded library

查看:36
本文介绍了通过在线程库中处理来消除对 Invoke() 的需求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在编写的类库中,我有一个方法允许库在不同的线程上做一些事情,比如:

Within a class library I'm writing I have a method allowing the library to go and do some stuff on a different thread which does something like:

    public void DoStuffAsync(AP p)
    {
        this.Running = true;
        this.Cancel = false;

        ParameterizedThreadStart threadStart = new ParameterizedThreadStart(DoStuff);
        Thread procThread = new Thread(threadStart);
        procThread.Start(p);
    }

我还在接口上声明了许多开发人员可以挂钩的事件,例如 StatusUpdate 和 ProgressUpdate.我目前正在编写一个小测试应用程序(目前在 WPF 中,尽管我希望在 WinForms 中具有相同的行为),它调用 DoStuffAsync() 然后更新进度条和标签.

I also have a number of events declared on the interface that the developer can hook into, such as StatusUpdate and ProgressUpdate. I'm currently writing a little test app (in WPF presently although I expect the same behaviour in WinForms) that calls DoStuffAsync() and then updates a progress bar and label.

不幸的是,第一遍我遇到了一个错误,通常的线程不是拥有控件的线程.我想要做的是消除用户在 UI 端调用 Invoke() 的需要,让他们只需订阅事件并让它们工作.

Unfortunately 1st pass I got an error, the usual thread not being the one which owns the controls. What I'd like to do is remove the need for the user to call Invoke() within the UI side, and for them to simply subscribe to the events and have them work.

那么问题是,在处理事件处理程序时,我的代码有没有办法做到这一点?目前像这样触发:

So the question, is there a way I can do this is my code when dealing with the event handlers? Currently trigger like so:

        public void UpdateProgress(object sender, ProgressEventArgs e)
        {
            if (handler != null)
            {
                handler(sender, e);
            }
        }

推荐答案

使用 AsyncOperationManager 代替.

它会为你做调用.(在内部,它使用 nobugz 描述的 SynchronizationContext)

It will do the invoke for you. (internally it uses the SynchronizationContext as nobugz describes)

这篇关于通过在线程库中处理来消除对 Invoke() 的需求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆