c#Getting Started-Asynchronous

block

There is now a command to get a txt file from your hard disk, the first word of the first line, and the second word of the second line until no words meet the requirements.
Getting the characters and splicing them together is the work of the cpu, which can be done quickly. However, getting a file from the hard disk can be a long time delay because the hard disk is old and not fast.
The CPU has nothing to do during this time, he just waits. This is called blocking.

An operation like this to get, write, and upload files is called an IO operation.
Whether from the hard disk or from the network, CPU is an instruction and does not require calculation.

Asynchronous and multithreaded

Asynchronous does not open up new threads, so there is no advantage to operations that require CPU computation. He is only used to solve the blocking problem caused by IO.

Use multithreading to split into two threads, one to continue waiting for files, and one to do later operations. This will have the same effect as asynchronous for this program.
But that blocked thread, for other programs, is in the maze. The problem of waste of resources has not been solved.

Task class

The asynchronous implementation of c#is based on the Task class. The Task class is still multi-threaded but optimized.

Simple multithreading

The Task class can simply create a multithreaded task using the Run method:

Task.Run(() =>
{
	for (int i = 0; i < 10; i++)
		Console.WriteLine("Task say"+i);
});
for (int i = 0; i < 10; i++)
	Console.WriteLine("Main thread says"+i);
Console.ReadLine();

The Run method received a delegate without parameters. This example is written using an anonymous method.
The thread created by this method is a background thread. When all foreground threads (the main thread is also the foreground thread) end, the program terminates directly without waiting for the background thread to finish.

Waiting Task

Multithreaded runs cannot predict order. If you want some degree of control over the order. You can call the Wait method of a running Task object.
This will wait until he finishes. If you are waiting for multiple tasks, you can use the WaitAll method of the Task class with an array of Tasks.

var task = Task.Run(() =>
  {
	  for (int i = 0; i < 100; i++)
		  Console.WriteLine("Task say" + i);
  });
task.Wait();
for (int i = 0; i < 100; i++)
	Console.WriteLine("Main thread says" + i);

A wait-only task can be created using the Delay method of the Task class. The parameter is the number of milliseconds to wait.

for (int i = 0; i < 100; i++)
{
	Task.Delay(100).Wait();
	Console.WriteLine(i);
}

Run with Return Value

The Run method can receive a parameterless delegate with a return value. You can then use the Result property to get the return value.

var task = Task.Run(() =>
  {
	  int sum = 0;
	  for (int i = 0; i < 10; i++)
		  sum += i;
	  return sum;
  });
Console.WriteLine(task.Result);

If the task is not completed, it will automatically wait until the task is completed.

asynchronous

await

The await keyword can be used within a method by prefixing the method return value with an async modifier.
Using the await keyword on a Task object returns execution privileges to the caller while waiting for the Task to complete.

Console.WriteLine("Program Start");
a();
Console.WriteLine("Program End");
Task.Delay(200).Wait();

async void a()
{
	Console.WriteLine("Method Start");
	await Task.Delay(100);
	Console.WriteLine("Method End");
}


If the Task object has a return value, awiait also gets its return value

Console.WriteLine("Program Start");
a();
Console.WriteLine("Program End");
Task.Delay(200).Wait();

async void a()
{
	Console.WriteLine("Method Start");
	var t = Task.Run(() => { Task.Delay(100).Wait(); return 100; });
	int i = await t;
	Console.WriteLine(i);
}

When await is encountered, it is assumed that the method has been completed and returns directly to the caller to continue running. When the method completes, a new thread is opened to continue the remaining steps.

async

When a method is modified by async, the return value of the method can only be void, Task, or Task with a return value.
But you don't need to create a Task object yourself and return it.
After adding async, your method will automatically take this form:

Task a()
{
	return Task.Run(() =>
	{
	//Your code
	});
}

Keywords: C#

Added by vivek on Thu, 03 Feb 2022 19:18:45 +0200