private void SyncProcess_Click(object sender, EventArgs e) { Stopwatch myWatch = new Stopwatch(); OperationWithTask obj = new OperationWithTask(); myWatch.Start(); textBox1.Text = obj.GetPrintContent(""); myWatch.Stop(); textBox1.Text = textBox1.Text + $"Total Time elapsed is {myWatch.ElapsedMilliseconds.ToString()}"; }
private async void AsyncWithNewTask_Click(object sender, EventArgs e) { Stopwatch myWatch = new Stopwatch(); OperationWithTask obj = new OperationWithTask(); Func <string, string> myNewFunc = new Func <string, string>(obj.GetPrintContent); Task <string> newTask = new Task <string>(() => myNewFunc("")); // This is how you pass a func or action that accepts input parameter myWatch.Start(); /*If the task has been created then it should be start to excute the function wrapped by it. Else it will not work*/ newTask.Start(); /*The below implementation will work howevr it is blocking the called thread who has called the method as used task.wait()*/ //newTask.Wait(); //textBox1.Text = newTask.Result; /*The below implementation will release the called thread (UI) and perform the work*/ textBox1.Text = await newTask; myWatch.Stop(); textBox1.Text = textBox1.Text + $"Total Time elapsed is {myWatch.ElapsedMilliseconds.ToString()}"; }
private async void AsyncWithTaskRun_Click(object sender, EventArgs e) { textBox1.Text = string.Empty; /* * We have seen what async/await does inside AsyncWithNewTask_Click method. * The same could be achieved using Task.Run, what we do here as Step 1 */ Stopwatch myWatch = new Stopwatch(); OperationWithTask obj = new OperationWithTask(); myWatch.Start(); textBox1.Text = await Task.Run <string>(() => obj.GetPrintContent("")); myWatch.Stop(); textBox1.Text = textBox1.Text + $"Total Time elapsed is {myWatch.ElapsedMilliseconds.ToString()}" + Environment.NewLine; /* * Step 2 ... Now we are going to change the code for * parallel execution */ textBox1.Text = textBox1.Text + "------------------" + Environment.NewLine + Environment.NewLine; await PrintWebSiteContentParallely(); }