Threading in C#

Delaying without blocking:
Thread.Sleep is a synchronous delay. If you want an asynchronous delay then use Task.Delay.

// Execution of the async method will continue one second later, but without blocking.
await Task.Delay(1000);

Task.Run vs Task.Factory.StartNew


Working with scheduled tasks:

TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();
var task = Task.Factory.StartNew(() =>
                                         //do some work here

task.ContinueWith(t => Thread.Sleep(1000), TaskScheduler.Default)
    .ContinueWith(t =>
                          //do more work here
                      }, ui);

Starting a Async task from a non-async method … such as static void Main():

private static void Main(string[] args)
	var myTask = GetIt();
	List<Instrument> result = myTask.Result;
private static async Task<List<Instrument>> GetIt()
	return await Task.Delay(10000); // DoSomeAsyncWorkHere...

What's your thoughts on this?


Protected by WP Anti Spam