Asynchronous programming is a set of techniques to implement expensive operations which are performed simultaneously with the rest of the program. Asynchronous programming is often used in the context of programs with a graphical user interface: it is generally unacceptable to freeze a user interface during the course of a time-consuming operation. In addition, asynchronous operations are important for server applications that need to manage multiple client requests simultaneously.
Background tasks
Sometimes when you execute an action, you do not need to wait for the result of this action, so you return the focus to the user for further events, for example, when you send an image to the server, the image resizing operation can be performed in the background. Here’s how to execute a task and to return the focus to the user : You just need to run a task with Task.Run() static method (available from .NET 4.5) If you work with .NET 4.0 Framework you need to use Task.Factory.StartNew() static method
using System;
using System.Threading.Tasks;
namespace MyApp
{
public class TestClass
{
public void DoWork()
{
Task.Run(() => { /* do something */});
}
}
}
Sometimes you have several independents actions of each other to execute, thus when you run the second task after the previous one had been completed, we say they are executed synchronously, to gain speed of execution and return control to the user faster we can execute asynchronously between it, in other words we parallelize these tasks : here’s how: I will use Task.Run() static method (available from .NET 4.5), but as the latest paragraph if you are using .NET 4.0 Framework you can use Task.Factory.StartNew() static method
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace MyApp
{
public class TestClass
{
public void DoWork()
{
/*Build an array of tasks wich return a value*/
Task
Like this:
LikeLoading...
Related posts
Written by
anthonygiretti
Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform.
He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.