Old async programming with callbacks/delegates/promises
Synchronous programming blocks the main thread, which in web apps typically results in the UI blocking and being unresponsive while some backend processing occurs.Asynchronous programming (such as C#'s Task<T> or javascript's promises) implement non-blocking asynchronous programming that frees up the UI to remain responsive by allowing the slow back end processing to occur in parallel (on another thread) and once it has completed proceeding with the program.
Historically this was achieved by the use of callbacks to signal the completion of the background operation. If you begin to execute a long running process you invoked it with as an input parameter a callback function / pointer-to-function / delegate that would be signalled (execution would jump to) on completion of the long running process. If program calls a long-running operation a you might pass in a delegate/the address of method b. When the operation a completes your program resumes in method b. If method b calls an async call to a long running process it may invoke it with a delegate of method c. It can quickly become confusing and hard to keep track of the program execution flow.
C# 5 New model
C#5 handles much of this behind the scenes, New asynchronous methods turn your code into a callback state machine that tracks and handles the program flow for you.Mark your method with a new "async" modifier
Return void or Task<T> (where T is the type you would have returned normally)
Use the await operator to yield control, i.e. await <methodname> where methodname is an asynchronous method.
Program flow resumes - in the same method - after the awaited method has completed - but in the mean time your UI has been responsive as normal. Thus your code looks and fields like good old synchronous code, even through it is executing asynchronously.
public Form1()
{
InitializeComponent();
ComputeStuffAsync();
}
private void Form1_Load(object sender, EventArgs e)
{
}
async void ComputeStuffAsync()
{
var sum = 0.0;
await Task.Run(() =>
{
for (var i = 0; i < 200000000; i++)
{
sum += Math.Sqrt(i);
}
} );
lblSum.Text = sum.ToString();
lblSumTxt.Text = "Once";
await Task.Run(() =>
{
for (var i = 0; i < 200000000; i++)
{
sum += Math.Sqrt(i);
}
});
lblSum.Text = sum.ToString();
lblSumTxt.Text = "Twice";
}
No comments:
Post a Comment