C# learning related series of multi-threading (7)---Task related attribute usage

1. The difference between Task and Thread

  1. The task is structured on the thread, and the final execution of the task must be given to the thread.
  2. There is not a one-to-one relationship between tasks and threads. Tasks are more like thread pools. Tasks have very little overhead and precise control compared to thread pools. (In general, the usage of Task is more advanced, and Task should be given priority when using multi-threads)

 2. Task related attributes

1.status Current status attributes (more) 

  • Created : The task has been initialized.
  • WaitingForActivation: Waiting for the .NET Framework infrastructure to internally activate and schedule it.
  • WaitingToRun: It has been scheduled to be executed, but execution has not yet started.
  • Running: Running, but not yet completed.
  • WaitingForChildrenToComplete: Completed execution and is implicitly waiting for attached subtasks to complete.
  • RanToCompletion: The executed task has been successfully completed.
  • The cancellation has been acknowledged by throwing an OperationCanceledException on its own CancellationToken while the token is in the signaled state, or the task's CancellationToken has been signaled before the task began executing.
  • Faulted: Task completed due to an unhandled exception.

2. CurrentId: The ID of the task currently being executed. (int)

3. IsCompleted: Whether the current task has been completed. (bool)

4. IsCanceled: Whether the task was completed due to cancellation. (bool)

5. ID: The Id of the current Task instance. (int)
6. TaskCreationOptions There are seven priorities for the current task:

  • None:Black recognition activity.
  • PreferFairness: Schedule tasks in a way that is as fair as possible, meaning tasks scheduled earlier will be more likely to run earlier, and tasks scheduled later will More likely to run later.
  • LongRuning: Specifies that the task will be a long-running, coarse-grained operation involving fewer and larger components than a fine-grained system. It is possible to create more threads than the number of available hardware threads through oversubscription. It will also prompt the task scheduler: The task requires additional threads so that the task does not block other threads or work items in the local thread pool queue from being pushed forward.
  • AttachedToParent: Specifies that the task is attached to a parent in the task hierarchy.
  • DenyChildAttach: Specifies that any attempts are executed as additional subtasks.
  • HideScheduler: Prevents the environment scheduler from being considered the current scheduler of the created task, the current scheduler.
  • RunContinuationsAsynchronously: Forcibly add continuation tasks to the current task.

 3. Commonly used methods of Task

1.Wait(task) Wait for the execution of the current task to end.

Code demo:

        Task tt = Task.Run(() =>
            {
                for (int i = 0; i < 300; i++)
                {
                    Console.Write(1);
                }
            });
            tt.Wait();
            for (int i = 0; i < 300; i++)
            {
                Console.Write(2);
            }
            Console.ReadKey();

When there is no tt.wait() in the code, the running results are 1 and 2 appearing alternately. Otherwise, 2 will be output after the tt task is completed, that is, after the output 1 is completed.

2. WaitAll() Wait for all tasks to be completed.
3. WaitAny() Wait for any task to be executed and then execute it.
4.ContinueWith() Automatically execute the next task after the first task ends.

Code demo:

            Task<int> tt = Task<int>.Run(() =>
            {
                for (int i = 0; i < 300; i++)
                {
                    Console.Write(1);
                    
                }
                return 10;
            });
            tt.ContinueWith(T1 =>
            {
                for (int i = 0; i < 300; i++)
                {
                    Console.Write(2);
                }
                Console.WriteLine("tt的结果为:"+T1.Result);
            });

The running result is:

The usage of ContinueWith is code that is executed after a task is completed. It should be noted that T1 returns the result for the previous task.
5.CancellationTokenSource Cancel a task.
 

Guess you like

Origin blog.csdn.net/qiaodahua/article/details/134095345