简体   繁体   English

C#,当主线程空闲时如何在主线程中运行函数

[英]C#, how to run a function in the main thread when the main thread becomes idle

I'm trying to port a Dart application to C#, in my dart app I use Futures to queue up functions asynchronously such that the queue will execute each subsequent function at some point in the future when it's turn comes in the VM's asynchronous call queue but importantly these are run in the "root thread". 我正在尝试将Dart应用程序移植到C#,在我的dart应用程序中,我使用Futures异步将函数排队,以使该队列将来在某个时候执行后续的每个函数,而轮到VM的异步调用队列了,但是重要的是,它们在“根线程”中运行。 I understand this is highly specific to the Dart VM, but I was wondering whether anything similar could be done in C#. 我了解这是Dart VM特有的,但是我想知道是否可以在C#中完成任何类似的工作。 I basically want to be able to pass a function which takes no arguments to some method or object which will call that function in the main thread when the main thread finds it has no more work to do. 我基本上希望能够将不带任何参数的函数传递给某个方法或对象,当主线程发现它不再需要工作时,该方法或对象将在主线程中调用该函数。 I should also say that my code is for a service, not a UI application. 我还应该说我的代码用于服务,而不是UI应用程序。

You can do that by creating your own custom SynchronizationContext , Stephen Toub has an article on how to do that here . 您可以通过创建自己的自定义SynchronizationContext来做到这一点 ,Stephen Toub在这里有一篇有关如何做到这一点的文章。 The SynchronizationContext is what is used to schedule work to be done. SynchronizationContext是用于安排要完成的工作的对象。 So by rolling your own, you need to keep a queue of the work to be done and then execute each action in the queue. 因此,通过滚动自己的脚本,您需要将要完成的工作保留在队列中,然后在队列中执行每个动作。

You can customize this so that when the queue is empty (ie the SynchronizationContext is idle) you execute the action that you need. 您可以对此进行自定义,以便在队列为空(即SynchronizationContext处于空闲状态)时执行所需的操作。 More info on contexts here . 有关上下文的更多信息,请参见此处

An effective way to send something to be executed to a particular SyncrhonizationContext is to use Task.Run . 将要执行的内容发送到特定SyncrhonizationContext的有效方法是使用Task.Run The code below will schedule your code to run in the current SC. 下面的代码将安排您的代码在当前SC中运行。 Using Task.Run without specifying a TaskScheduler will schedule the work on a thread pool thread. Task.Run不指定TaskScheduler情况下使用Task.Run将在线程池线程上安排工作。

Task.Run( () =>/* you code */, CancellationToken.None, TaskScheduler.FromCurrentSynchronizationContext());

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

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