简体   繁体   English

C#:Task.Run 在主线程上执行

[英]C#: Task.Run execute on main thread

I am using monotouch/Xamarin for an iOS app.我正在为 iOS 应用程序使用 monotouch/Xamarin。

The documentation for Task.Run states: Task.Run的文档指出:

Queues the specified work to run on the ThreadPool and returns a task handle for that work.将指定的工作排入队列以在 ThreadPool 上运行并返回该工作的任务句柄。

Which essentially indicates that it could run on any thread ThreadPool .这实质上表明它可以在任何线程ThreadPool上运行。

I want to do something like:我想做类似的事情:

Task.Run(async () => await PerformTask());

but have it run on the main thread.但让它在主线程上运行。 Normally I would write it using BeginInvokeOnMainThread as follows:通常我会使用BeginInvokeOnMainThread编写它,如下所示:

BeginInvokeOnMainThread(async () => await PerformTask());

But I am doing this in shared code and do not want to use iOS specific calls.但我在共享代码中这样做,不想使用 iOS 特定的调用。 Is there a way for me to tell Task.Run() to invoke the action on the main thread?有没有办法告诉 Task.Run() 调用主线程上的操作?

If you want to run PerformTask in the current thread, instead of a thread pool thread, you simply need to not call Task.Run .如果您想在当前线程中运行PerformTask而不是线程池线程,您只需不要调用Task.Run Just use:只需使用:

PerformTask();

and you're done.你就完成了。 If you want to only continue executing the rest of the method when that task is done, then await it:如果您只想在该任务完成后继续执行方法的其余部分,请await它:

await PerformTask();

There is no reason to call Task.Run here for you, nor is there any reason to create a lambda that awaits the method for no particular reason (you could just call it directly if you wanted to start it from a thread pool thread).没有理由在此处为您调用Task.Run ,也没有理由创建一个 lambda 来无缘无故地awaits该方法(如果您想从线程池线程启动它,则可以直接调用它)。

Have a look at MainQueue.cs:https://gist.github.com/gering/0aa9750d3c7d14b856d0ed2ba98374a8看看 MainQueue.cs:https ://gist.github.com/gering/0aa9750d3c7d14b856d0ed2ba98374a8

It is for Xamarin Forms applications.它适用于 Xamarin Forms 应用程序。 You have to call Init() from main thread once, but then you are able to ensure execution on main thread.您必须从主线程调用 Init() 一次,但是您可以确保在主线程上执行。

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

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