Application.Current.Dispatcher.Invoke() 来自一个动作

Application.Current.Dispatcher.Invoke() from within an action

我有一个问题,我 运行 部分代码使用 Application.Current 命名空间中的 Dispatcher class。然后我想使用 Dispatcher.Invoke().

返回的任务的 ContinueWith 方法构造后续操作

在这种特殊情况下,后续操作也需要在 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()调用的位置。但是,第二种方法不起作用,代码没有被调用,我不知道为什么。

我没有得到什么?

我设法解决了我的问题,放弃了 ContinueWith()。有效

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

                        followUpAction();
                    });

感谢您的宝贵意见。