What is Async and Await and why do we need it?
In .NET Framework 4.0 the Task Type was introduced which greatly simplified the asynchronous programming check out my article on Tasks here.
With .NET Framework 4.5 comes C# 5.0 and brings along Async and Await which makes its writing asynchronous programs same a writing synchronous codes,will discuss more on that .
We all know when a method is called , the control only returns to the caller once the method is executed , this behavior is called synchronous .
Check out the below code
private void Button_Click(object sender, RoutedEventArgs e)
{
Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
Result.Text += Environment.NewLine;
SimulateLongProcess();
Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
Result.Text += Environment.NewLine;
}
void SimulateLongProcess()
{
Longrunningtask();
}
///
/// Simulating Long Running Task
///
///
void Longrunningtask()
{
for (int i = 0; i < int.MaxValue; i++)
{
}
}
The Above code will freeze your UI as heavy computing is done on the main thread,
you can either spin of a thread on every click of the button, or use tasks (better suited to the scenario) ,
Updated the above code to use task
Updated the above code to use task
private void Button_Click(object sender, RoutedEventArgs e)
{
Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
Result.Text += Environment.NewLine;
SimulateLongProcess();
}
void SimulateLongProcess()
{
Longrunningtask();
}
///
/// Simulating Long Running Task
///
///
void Longrunningtask()
{
Task.Run(() =>
{
for (int i = 0; i < int.MaxValue; i++)
{
}
Dispatcher.BeginInvoke((Action)(() =>
{
Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
Result.Text += Environment.NewLine;
}
));
});
}
}
Task does solve the problem of freezing the UI as the heavy computing is thread pooled and then returned back to the main thread after completion of the task , if you compare the code of the synchronous execution and asynchronous exception, there is a quite a bit if difference , The Async and Await make the asynchronous Code look more like Synchronous code
Check the Code update to use async await below:
Check the Code update to use async await below:
private async void Button_Click(object sender, RoutedEventArgs e)
{
Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
Result.Text += Environment.NewLine;
await SimulateLongProcessAsync();
Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
Result.Text += Environment.NewLine;
}
async Task SimulateLongProcessAsync()
{
await LongrunningtaskAsync();
}
///
/// Simulating Long Running Task
///
///
async Task LongrunningtaskAsync()
{
await Task.Run(() =>
{
for (int i = 0; i < int.MaxValue; i++)
{
}
});
}

0 comments:
Post a Comment