Async & Await for Beginners

In response to the complexity of Threading in .Net, async and await keywords step in .Net 4.5 to make asynchronous programming easier. Asynchrony is quite essential when doing certain tasks like: calling web services, working with files and working with images. Microsoft technologies like Windows 8 and Windows Phone rely heavily on this new async programming.

So here is an elementary sample on async and await:

        public Foo()
        {
            LazyMethod();
            displayMessage = "Getting Message…";
        }                
        private async void LazyMethod()
        {
            string result = await LazyMethodAsync("Geeks live longer");
            displayMessage = result;
        }

        private Task<string> LazyMethodAsync(string message)

        {
            return Task.Run<string>(() => "Welcome to " + message);

        }

Async and await are always a pair. You can have multiple awaits in one method as long as it is marked async.

For more visit full msdn documentation.

This entry was posted in C# and tagged , , , , , . Bookmark the permalink.

Leave a reply

*