Sunday 12 October 2014

Task and synchrony

Task class is a pretty nifty one and helps in implementing much of the plumbing required to use CLR ThreadPool and makes application developers focus on making their application more responsive. However there can be some cases where after implementing a highly scalable API, you get a requirement to integrate that with an application which does not use asynchrony at all. A similar requirement can be that you need to invoke an async method from constructor of a class.

There is an easy way to do that. Use Task.WaitAll for asynchronous methods that have return type void and use Task.FromResult or Task.Run for asynchronous methods that return some result. Simple example:

static void Main(string[] args)
{
            Console.WriteLine("Starting");
            DoSomethingSynchronously(1000);
            Console.WriteLine("Finished");
            Console.WriteLine("Starting");
            DoSomething2Synchronously(1000);
            Console.WriteLine("Finished");
            Console.ReadLine();
}

static private void DoSomething2Synchronously(int x)
{
            FunctionTesting t = new FunctionTesting();
            var y = t.DoSomething2Async(100);
            Task.WaitAll(y);
}

static private void DoSomethingSynchronously(int x)
{
            FunctionTesting t = new FunctionTesting();
            var y = Task.FromResult(t.DoSomethingAsync(100).Result).Result;
            Console.WriteLine(y);
}

class FunctionTesting
{
        public async Task DoSomethingAsync(int x)
        {
            await Task.Delay(3000);
            Console.WriteLine(x);
            return "xxxxxxxx";
        }

        public async Task DoSomething2Async(int x)
        {
            await Task.Delay(3000);
            Console.WriteLine(x);
        }
}

No comments:

Post a Comment