来自操作中的Application.Current.Dispatcher.Invoke()

时间:2015-04-08 14:47:43

标签: c# multithreading async-await invoke

我遇到问题,我使用Dispatcher命名空间中的Application.Current类运行部分代码。然后我想使用ContinueWith返回的任务的Dispatcher.Invoke()方法构建一个跟进操作。

在这种特殊情况下,后续操作需要在UI线程内运行,因此需要再次将其包含在Dispatcher.Invoke中。这就是我开始工作的方式:

Action doSomeMoreStuff = () => { this.MoreStuff; }
Application.Current.Dispatcher.Invoke(() => this.DoStuff).ContinueWith(x => Application.Current.Dispatcher.Invoke(this.DoSomeMoreStuff));

但是我想保持它的通用性,并且可能存在我不希望从UI线程中运行后续代码的情况。所以我试着封装后续代码本身:

Action doSomeMoreStuff = () => { Application.Current.Dispatcher.Invoke(this.MoreStuff); }
Application.Current.Dispatcher.Invoke(() => this.DoStuff).ContinueWith(x => this.DoSomeMoreStuff);

据我了解这个问题,我只是改变了Application.Current.Dispatcher.Invoke()电话的位置。但是,第二种方法不起作用,代码没有被调用,我不明白为什么。

我没有到这里来的是什么?

1 个答案:

答案 0 :(得分:1)

我设法解决了我的问题,放弃了ContinueWith()。它的工作原理

Action followUpAction = () => { };
Application.Current.Dispatcher.Invoke(
                async () =>
                    {
                        await this.DoStuff()

                        followUpAction();
                    });

感谢您提供的有用评论。