简体   繁体   English

任务。运行引发事件的方法

[英]Task.Run a method who raise events

In a Windows Store application, written in WPF and C#, I need to launch an async method who gather informations from files. 在用WPF和C#编写的Windows Store应用程序中,我需要启动一个异步方法,该方法从文件中收集信息。 But I want it to run in background while to UI is responsive to user interactions. 但是我希望它在UI响应用户交互时在后台运行。 So, I did this : 所以,我这样做:

Task x = Task.Run(async () => await Method());

The problem is, "Method" must raise change notifications to the UI. 问题是,“方法”必须向用户界面发出更改通知。 As you can expect, it crashed because the method who raise the event is not in the UI thread. 如您所料,它崩溃是因为引发事件的方法不在UI线程中。

So, I did this : 所以,我这样做:

TaskScheduler t = TaskScheduler.FromCurrentSynchronisationContext();
Task x = Task.Run(() => {}).ContinueWith(async _ => await Method(), t);

My question is, as I must specify a synchronization context, and as there is no way to specify it in the Run method, is there a way to do something like this : 我的问题是,由于我必须指定一个同步上下文,并且由于无法在Run方法中指定它,因此有没有办法执行以下操作:

TaskScheduler t = TaskScheduler.FromCurrentSynchronisationContext();
Task x = Task.ContinueWith(async _ => await Method(), t);

Or, if you have another suggestion to make it work, it is welcome. 或者,如果您有其他建议可以使它起作用,则欢迎您。

Thank you. 谢谢。

You dont need to spin up a new Task at all. 您根本不需要启动新Task You can simply await Method() without needing to use ContinueWith on Task which consumes a ThreadPool thrrad.. When you await on an async method, it will run synchronously until hitting the first await and return back to the calling method, which will keep your UI responsive 您可以简单地await Method()而无需在使用了ThreadPool thrrad的Task上使用ContinueWith 。.当您await异步方法时,它将同步运行,直到遇到第一个await并返回到调用方法为止,这将使您UI响应

You can simply 你可以简单地

await Method();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM