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);
        }
}

Monday 6 October 2014

StackOverflowException - Quite obvious

It isn't all that difficult to hit StackOverflowException as opposed to what I would typically like to believe.

Create a console application with default settings. Add a simple class which has a single method which calls itself recursively.




Call the function from the Main function. e.g.



This produces error. If it doesn't then try changing the value such that it starts to produce the error :).


Lower the value to like 3000 instead of 3371. And we get a successful response.



Always interesting to break software. At least sometimes.