Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

I. Task

1. Task definition
Task was created in FarmWork3.0 and uses threads from a thread pool, all background threads, with a powerful API.Copy the code
The difference between tasks and threads:
1. Tasks are built on top of threads, which means tasks are ultimately thrown to threads to execute. 2. Tasks do not have a one-to-one relationship with threads. For example, opening 10 tasks does not mean opening 10 threads.Copy the code
2. Task usage
1, Task. Run (Action act); 2, taskFactory. StartNew (Action act); Var task = new task (() =>{}).start ();Copy the code
Common apis for Task

Parallel

Much like task, starting multiple threads is equal to Task + waitAll, since the main thread also participates in the calculation.Copy the code
Parallel.ForEach(new int[] { 0, 1, 2, 3, 4 }, options, (t, state) => { this.DoSomethingLong($"btnParallel_Click_00{t}");  // End all state.stop (); // Stop the current state.break (); return; });Copy the code

Thread exception handling, thread cancellation, multithreaded temporary variables and lock

1. Thread exception handling
Exceptions in multiple threads are swallowed unless WaitAll makes the main thread waitCopy the code
for (int i = 0; i < 20; i++) { string name = string.Format($"btnThreadCore_Click_{i}"); Action<object> act => {// Try {thread.sleep (2000); If (t.tostring ().equals ("btnThreadCore_Click_11")) {throw new Exception(string.format ($"{t} failed to execute ")); } if (t.tostring ().equals ("btnThreadCore_Click_12")) {throw new Exception(string.format ($"{t} failed to execute ")); } console. WriteLine("{0} succeeded ", t); } catch (Exception ex) { Console.WriteLine(ex.Message); }}; taskList.Add(taskFactory.StartNew(act, name)); }Copy the code
2. Thread cancellation
Thread cancellation is not an operation of the thread, but the operation of the semaphore (shared variables: multiple can access the data). 2. Each thread in the execution process, intermittently check the semaphore, and then terminate itselfCopy the code

CancellationTokenSource: IsCancellationRequested (); CancellationTokenSource: IsCancellationRequested (); cancel() 3. In the case of some task not being started, it will be cancelled if the cancellation request has been sent

3, multithreaded temporary variable problems
1. Sharing occurs if multiple threads share a variable. 2. Assigning values inside a loop means that each thread corresponds to a variable objectCopy the code
//int k; //int k; for (int i = 0; i < 5; i++) { int k = i; new Action(() => { Thread.Sleep(100); //Console.WriteLine(k); // Console.WriteLine(i); }).BeginInvoke(null, null); }Copy the code
4. Thread-safe Lock

Shared variables: all have access to local variables/global variables/a value of the database/disk files

private int TotalCount = 0; for (int i = 0; i < 10000; Taskfactory.startnew (() => {this.TotalCount += 1; }); }Copy the code

> Resolve thread insecurity

Use thread-safe collection ConcurrentDictionary (ConcurrentDictionary)Copy the code

Use locks with caution

1. The lock method block is single-threaded; 3. Lock (this) locks the current instance. 4. Lock (' STR ') because of memory allocation in share mode, string values are unique and lock other variablesCopy the code
private int TotalCount = 0; Private static readOnly object _lock= new object(); for (int i = 0; i < 10000; Taskfactory.startnew (() => {lock(_lock) {this.TotalCount += 1; }}); }Copy the code

Four, await async

Await Async is syntactic sugar and is a function provided by the compiler.Copy the code
Private static async Task NoReturn() {console. WriteLine("111"); Task Task = taskfactory.startNew (() => {console. WriteLine(" child thread execution starts "); Thread.Sleep(3000); Console.WriteLine(" Child thread completes execution "); }); // the main thread returns at this point, and executes the main thread task await task; WriteLine(" execute callback "); // The thread of this callback is not specified: it may be the main thread or a child thread. }Copy the code
Async task == async void; async task == async void; async task == async voidCopy the code
Internal implementation principle uses the state machine to implement IAsyncStateMachine