C # Task TaskFactory asynchronous thread / asynchronous tasks

Task is .NetFramework3.0 appears, it is based on the thread pool thread, and then provides a rich API

TaskFactory   provide support for creating and scheduling Task objects

Create and start asynchronous tasks

1、Task task = new Task(() => ThreadPoolHelper.DoSomeThing());
      task.Start();

2、Task task = Task.Run(() => ThreadPoolHelper.DoSomeThing());

3、TaskFactory taskFactory = Task.Factory;

      Task task = taskFactory.StartNew(() => ThreadPoolHelper.DoSomeThing());

Task thread from the thread pool is, if you say I want to control the number of concurrent under Task, how to do?

. 1              {
 2                  // ThreadPool.SetMaxThreads (. 8,. 8);
 . 3                  // thread pool is a single embodiment, the globally unique
 4                  // After setting, the concurrent Task only 8; and threads are multiplexed;
 5                  / / global, please, do not set! ! ! 
. 6                  for ( int I = 0 ; I < 100 ; I ++ )
 . 7                  {
 . 8                      int K = I;
 . 9                      Task.Run (() =>
 10                      {
 . 11                          Console.WriteLine ($ "This is k={k},i={i} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}");
12                         Thread.Sleep(2000);
13                     });
14                 }
15             }
View Code

Run the above code we found several important considerations:

1, the value of i is equal to 100, since the asynchronous thread to start the main thread is not blocked;

2, disposed after use ThreadPool.SetMaxThreads method, although can be effective, but the embodiment is a single thread pool, globally unique, this setting affects the whole process;

So how do you achieve?

 1             {
 2                 List<Task> taskList = new List<Task>();
 3                 for (int i = 0; i < 10000; i++)
 4                 {
 5                     int k = i;
 6                     if (taskList.Count(t => t.Status != TaskStatus.RanToCompletion) >= 20)
 7                     {
 8                         Task.WaitAny(taskList.ToArray());
 9                         taskList = taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
10                     }
11                     taskList.Add(Task.Run(() =>
12                     {
13                         Console.WriteLine($"This is {k} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}");
14                         Thread.Sleep(2000);
15                     }));
16                 }
17             }
View Code

Can also be achieved using Parallel

Task common method

1、Delay(Int32)、Delay(Int32, CancellationToken)、Delay(TimeSpan)、Delay(TimeSpan, CancellationToken)

Mission after a specified time

1             {
2                 Stopwatch stopwatch = new Stopwatch();
3                 stopwatch.Start();
4                 Console.WriteLine("在Delay之前");
5                 Task.Delay(2000).ContinueWith(t => { Console.WriteLine($"Delay耗时ContinueWith Start{stopwatch.ElapsedMilliseconds}"); ThreadPoolHelper.DoSomeThing(); Console.WriteLine($"Delay耗时ContinueWith End{stopwatch.ElapsedMilliseconds}"); });
6                 Console.WriteLine($"Delay time consuming stopwatch.ElapsedMilliseconds} { " );
 . 7              }
View Code

2、ContinueWith(Action<Task,Object>, Object)、ContinueWith(Action<Task>)、ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)、...

After the completion of objectives and tasks asynchronously execute a continuation of the mission

3、Wait()、Wait(CancellationToken)、Wait(Int32)、Wait(Int32, CancellationToken)、Wait(TimeSpan)

After waiting for a task or action until the specified time and Thread.Join method, waitHandle.WaitOne method is quite

4、WaitAll(Task[])、WaitAll(Task[], CancellationToken)、WaitAll(Task[], Int32)、WaitAll(Task[], Int32, CancellationToken)、WaitAll(Task[], TimeSpan)

Wait for all tasks or objects to complete execution until the elapse of a specified time, or wait until canceled

5、WaitAny(Task[])、WaitAny(Task[], CancellationToken)、WaitAny(Task[], Int32)、WaitAny(Task[], Int32, CancellationToken)、WaitAny(Task[], TimeSpan)

Wait for all objects of any task to perform or complete a task object until the elapse of a specified time, or until the cancellation mark canceled

6、WhenAll(IEnumerable<Task>)、WhenAll(Task[])、WhenAll<TResult>(IEnumerable<Task<TResult>>)、WhenAll<TResult>(Task<TResult>[])

When all tasks have been completed objects, create and perform a new task

7、WhenAny(IEnumerable<Task>)、WhenAny(Task[])、WhenAny<TResult>(IEnumerable<Task<TResult>>)、WhenAny<TResult>(Task<TResult>[])

All task objects to complete any one task creates a new task and perform

TaskFactory common method

1、ContinueWhenAll(Task[], Action<Task[]>)、ContinueWhenAll(Task[], Action<Task[]>, CancellationToken)、ContinueWhenAll(Task[], Action<Task[]>, CancellationToken, TaskContinuationOptions, TaskScheduler)、...

When all tasks have been completed objects, create a new task and perform equivalent to the effect of the method Task.WhenAll

2、ContinueWhenAny(Task[], Action<Task>)、ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[], Action<Task<TAntecedentResult>>)、...

All task objects to complete any one task to create a new task and perform Task.WhenAny method considerable role

 

So when can multithreading? The task can be complicated by time

Multithreading can be doing? Lifting speed / optimize the user experience

Home: A Database Interface B C D services distributed search engine, suitable for multi-threaded, after the completion of all to return to the user, need to wait WaitAll
List: Core data may come from a database / interface service / distributed search engine / cache, multi-threaded concurrent requests, which will be completed by the results of which, the other on the matter

Examples reality

--- people to develop multi-threaded - to enhance the efficiency / performance

 1             {
 2                 TaskFactory taskFactory = new TaskFactory();
 3                 List<Task> taskList = new List<Task>();
 4                 taskList.Add(taskFactory.StartNew(o=> Coding("A", " Portal"), "A"));
 5                 taskList.Add(taskFactory.StartNew(o=> Coding("B", "    DBA"), "B"));
 6                 taskList.Add(taskFactory.StartNew(o=> Coding("C", " Client"), "C"));
 7                 taskList.Add(taskFactory.StartNew(o=> Coding("D", "Service"), "D"));
 8                 taskList.Add(taskFactory.StartNew(o=> Coding("E", " Wechat"), "E"));
 9 
10                 //Who completed the first, obtaining a red reward 
. 11                  taskFactory.ContinueWhenAny (taskList.ToArray (), T => Console.WriteLine ($ " {} t.AsyncState developed, obtaining a red reward {Thread.CurrentThread.ManagedThreadId.ToString ( " 00 " )} " ));
 12                  // after completion of combat operations, together celebrate 
13                  taskList.Add (taskFactory.ContinueWhenAll (taskList.ToArray (), RArray => Console.WriteLine ($ ' development are completed, together Thread.CurrentThread.ManagedThreadId.ToString celebrate {( " 00 " )} " )));
 14                  // ContinueWhenAny ContinueWhenAll non-blocking callback; and threads may be using a new thread, it may be just a thread to complete the task, The only main thread can not be
 15  
16 
17                  // blocks the current thread, waiting for a task to complete any 
18                  Task.WaitAny (taskList.ToArray ()); // can also limit wait 
19                  Console.WriteLine ( " ready to begin deployment environment " );
 20                  // need to be able to wait all thread to complete the task and then continue to block the current thread, waiting for the completion of all tasks 
21                  Task.WaitAll (taskList.ToArray ());
 22                  Console.WriteLine ( " after five modules completed, focus on debugging " );
 23  
24-                  // task .WaitAny WaitAll current thread is blocked, and other operations performed after the completion of the task
 25                  // blocking interface card, in order to control the concurrent and sequential 
26              }
View Code
 1         /// <summary>
 2         /// 模拟Coding过程
 3         /// </summary>
 4         /// <param name="name"></param>
 5         /// <param name="projectName"></param>
 6         private static string Coding(string name, string projectName)
 7         {
 8             Console.WriteLine($"****************Coding Start  {name} {projectName}  {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
 9             long lResult = 0;
10             for (int i = 0; i < 1_000_000_000; i++)
11             {
12                 lResult += i;
13             }
14             Console.WriteLine($"****************Coding   End  {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {lResult}***************");
15             return name;
16         }
View Code

Microsoft document:

Task:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.task?view=netframework-4.8

TaskFactory:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.taskfactory?view=netframework-4.8

Guess you like

Origin www.cnblogs.com/Dewumu/p/11821327.html