Is it possible to force a task to execute synchronously, on the current thread?
That is, is it possible, by e.g. passing some parameter to StartNew()
, to make this code:
Task.Factory.StartNew(() => ThisShouldBeExecutedSynchronously());
behave like this:
ThisShouldBeExecutedSynchronously();
Background:
I have an interface called IThreads
:
public interface IThreads { Task<TRet> StartNew<TRet>(Func<TRet> func); }
I would like to have two implemenetations of this, one normal that uses threads:
public class Threads : IThreads { public Task<TRet> StartNew<TRet>(Func<TRet> func) { return Task.Factory.StartNew(func); } }
And one that does not use threads (used in some testing scenarios):
public class NoThreading : IThreads { public Task<TRet> StartNew<TRet>(Func<TRet> func) { // What do I write here? } }
I could let the NoThreading
version just call func()
, but I want to return an instance of Task<TRet>
on which I can perform operations such as ContinueWith()
.
Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR. But that depends on the actual implementation of the task.
Task. Delay does not create new Thread, but still may be heavy, and no guaranties on order of execution or being precise about deadlines.
Task. Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!
A task is something you want done. A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.
You can simply return the result of func()
wrapped in a Task
.
public class NoThreading : IThreads { public Task<TRet> StartNew<TRet>(Func<TRet> func) { return Task.FromResult(func()); } }
Now you can attach "continue with" tasks to this.
Task scheduler decides whether to run a task on a new thread or on the current thread. There is an option to force running it on a new thread, but none forcing it to run on the current thread.
But there is a method Task.RunSynchronously()
which
Runs the Task synchronously on the current TaskScheduler.
More on MSDN.
Also if you are using async/await
there is already a similar question on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With