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". I understand this is highly specific to the Dart VM, but I was wondering whether anything similar could be done in 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.
Asked
Active
Viewed 713 times
0
-
There is no default mechanism in a service to get code to execute on a specific thread. Nor is one needed, a service doesn't have the thread safety problems that an UI thread has. If you still think this is necessary then you'll need to solve the [producer/consumer problem](https://en.wikipedia.org/wiki/Producer-consumer_problem), best done by leveraging existing solutions like Application.Run(). Like [this one](http://stackoverflow.com/a/21684059/17034). – Hans Passant May 21 '14 at 10:56
1 Answers
1
You can do that by creating your own custom SynchronizationContext
, Stephen Toub has an article on how to do that here. The SynchronizationContext
is what is used to schedule work to be done. 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 (i.e. the SynchronizationContext
is idle) you execute the action that you need. More info on contexts here.
An effective way to send something to be executed to a particular SyncrhonizationContext
is to use Task.Run
. The code below will schedule your code to run in the current SC. Using Task.Run
without specifying a TaskScheduler
will schedule the work on a thread pool thread.
Task.Run( () =>/* you code */, CancellationToken.None, TaskScheduler.FromCurrentSynchronizationContext());

NeddySpaghetti
- 13,187
- 5
- 32
- 61