Use Task Parallel Library -TPL (Task Parallel Libiry)

  We learn what is the thread in the previous section, how to use threads, and why you need the thread pool. Use thread pool can enable us to save operating system resources to reduce the degree of parallelism spending . We can think of the thread pool is an abstraction layer that hides the details of the use of threads to the programmer , so that we can focus on application logic rather than a variety of threads, problems.
  However, using a thread pool is also quite complex . From worker threads in the thread pool get results it is not easy . We need to implement, customize the way to get results, and if there is an exception occurs, an exception needs to be properly propagated to the initial thread. In addition to this, other than to create a group of related asynchronous operation, and to achieve a logical next operation will be performed after the completion of the implementation of the current operation is not easy. In the process of trying to solve these problems, we create asynchronous programming model and event-based asynchronous mode. Event-based asynchronous mode mentioned in Chapter 3. These patterns make it easier to get results, abnormal spread more easily, but the group together multiple asynchronous operations still need a lot of work, need to write a lot of code.
  In order to solve all the problems, .Net Framework4.0 introduces a new API on asynchronous operation, it is called. Task Parallel Library (Task Parallel Library, referred to as TPL) , .Net Framework version 4.5 of the API has been slight improvements , easier to use. The project will use the latest version of the book TPL, namely .Net Framework version 4.5 API, TPL can be viewed as yet another abstraction layer on top of the thread pool, which hides the underlying code programmers to interact with the thread poolAnd provides a more convenient grained APL, the core concept of the TPL is the task. A task represents an asynchronous operation that can run a variety of ways, it can run with or without the use of a separate thread. In this chapter, the task of exploring the use of all the details.
  By default, the programmer need not know how to perform the task actually. TPL creating a layer of abstraction by hiding implementation details to the user's tasks. Unfortunately, in some cases this can lead to subtle errors, such as when trying to obtain the results of the task of the program is suspended. This chapter helps to understand the underlying principles of TPL, and how to avoid inappropriate use.
  A task can be combined in various ways and other tasks. For example, you can start multiple tasks at the same time, wait for all tasks to complete, and then run a task on the results of all the tasks previously carried out some calculations. TPL compared with the previous model, which has a key advantage is its convenience for combining tasks of API ,
processing tasks in a variety of ways abnormal results. Since a task may be a number of other tasks, any of these, works may in turn have their own sub-task, so the concept of a AggregateException. This anomaly may be captured inside all abnormal level tasks, and allows separate handle these exceptions.
And, last but not least, C # 5.0 has built-in support for TPL, allowing us to use the new async and await keywords in a smooth , comfortable way operational tasks.
  In this chapter we will learn to perform asynchronous operations using TPL. We will learn what tasks, how to create a task in a different way, and how to combine tasks. We will discuss how the legacy APM and EAP task mode to use, and how to properly handle exceptions, how to cancel the task, and how to perform multiple tasks simultaneously. In addition, the task will be how to use correctly in Windows GUI applications.

class Program
{
    static void Main(string[] args)
    { 
     // create two tasks Task constructor [Start method call only these tasks, tasks will Task]
var T1 = new new Task (() => TaskMethod ( " Task. 1 " )); var T2 = new new the Task (() => TaskMethod ( " the Task 2 " )); t2.Start(); t1.Start (); // using Task constructor ======= different tasks Task.Run and Task.StartNew method created will begin immediately, without displaying call the Start method; Task.Run (()

     
=> TaskMethod ( " the Task. 3 " )); Task.Factory.StartNew (() => TaskMethod ( " the Task. 4 " ));

a method of simply Task.Factory.StartNew //Task.Run shortcut, but the latter has additional options.
// we mark the task to run for a long time, the results of the task will not use the thread pool, and run in a separate thread Task.Factory.StartNew (()
=> TaskMethod ( " Task 5 " ), TaskCreationOptions.LongRunning) ; Thread.Sleep(TimeSpan.FromSeconds(1)); Console.ReadKey(); } static void TaskMethod(string name) { Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); } }

  When the program runs, we use the Task constructor creates two tasks. We pass a lambda expression as the Action delegate. This allows us to provide TaskMethod a string parameter. Then run these tasks using the Start method.
Please note that only calls the Start method these tasks, will perform the task. It is easy to forget that the real task starts.
  Then use Task.Run and Task.Factory.StartNew way to run the other two tasks. Use Task constructor with the difference that these two tasks are created will begin work immediately, so no need to explicitly call the Start method for these tasks. All tasks from Task 1 to Task 4 have been placed on a thread pool thread and run in an unspecified order. If you run the program several times, you will find the task execution order is uncertain.
  Task.Run method is only Task.Factory.StartNew of a shortcut, but the latter have additional options. Pass! Normally if no special requirement, a method can be used before, Task 5 as shown in FIG. We marked the long-running task, the results of the task will not use the thread pool, and run in a separate thread. However, according to the current task scheduler to run the task (task scheduler) mode of operation may vary.

Guess you like

Origin www.cnblogs.com/gougou1981/p/12602841.html