# C # in Task Creation Guide

This article is still in the draft stage, it is inevitable there are modifications to correct the error, the logic is not very clear, we will strive to improve the long-term update!

[0000] Introduction

The title got up some "big", is intended to set our strengths, summed up the knowledge summary report on the Task relatively "right", welcomed the audience valuable advice! In this article the author comes from a variety of questions in the coding of the time, from the asynchronous programming curious process of actually running in the operating system. Usually use Task trembling, both want to improve efficiency, it is not afraid of control, chaos everywhere. If so, it is better to take a moment to understand its mystery of it! Just do IT.

[0001] Why do you want to write asynchronous code

New applications widely used file and network I / O. I / O API usually blocked by default, resulting in a poor user experience and hardware utilization, unless it challenging to learn and use patterns hope. Asynchronous API and language-level task-based asynchronous programming model has changed this model, only need to know a few new concepts can be executed asynchronously by default.

Asynchronous code has the following characteristics:

  • Waiting for I / O requests and returns, the thread may process more requests by generating additional server request.
  • While waiting for I / O requests to generate interactive UI thread, and by converting long-running job to another CPU core, so that the response speed faster UI.
  • Many newer .NET APIs are asynchronous.
  • Write asynchronous code in .NET is very simple!

Source: https://docs.microsoft.com

[0010] Asynchronous on the C # programming model

.NET provides three modes to perform asynchronous operations:

  • Task-based asynchronous mode (the TAP) , the single mode indicates a method of starting and completing asynchronous operation. TAP is introduced in the .NET Framework 4. This is the recommended method for asynchronous programming in .NET. In C # async and await keywords as well as in Visual Basic Async and Await operator for the TAP added language support. For more information, see the task-based asynchronous mode (TAP) .

  • Event-based asynchronous mode (EAP), to provide asynchronous behavior based on the old model events. This model requires the suffix Asyncmethod, and one or more events, event handler delegate type and EventArgderived types. EAP is introduced in the .NET Framework 2.0. Proposed new development no longer used in this mode. For more information, please refer -based asynchronous pattern of events (EAP) .

  • Asynchronous Programming Model (APM) mode (also known as IAsyncResult mode), this is the old model using IAsyncResult interface provides asynchronous behavior. In this mode, synchronization needs Beginand Endmethods (e.g., BeginWriteand EndWriteto achieve asynchronous write operation). Not recommended for new development to use this mode. For more information, see Asynchronous Programming Model (APM) .

Compare Mode

For comparison the fast asynchronous mode of operation of these three modes, consider using the specified offset from the read buffer to provide a specified amount of data in the Readmethod:

public class MyClass  
{  
    public int Read(byte [] buffer, int offset, int count);  
}  

This method will be disclosed in the following corresponding single TAP ReadAsyncmethods:

public class MyClass  
{  
    public Task<int> ReadAsync(byte [] buffer, int offset, int count);  
}  

EAP set corresponding to the following disclosure and members of the type:

public class MyClass  
{  
    public void ReadAsync(byte [] buffer, int offset, int count);  
    public event ReadCompletedEventHandler ReadCompleted;  
}  

Corresponding to the APM disclosed BeginReadand EndReadmethods:

public class MyClass  
{  
    public IAsyncResult BeginRead(  
        byte [] buffer, int offset, int count,   
        AsyncCallback callback, object state);  
    public int EndRead(IAsyncResult asyncResult);  
}  

Source: https://docs.microsoft.com

Dividing line, unfinished region --------------------------------

[0011] Practice

Use Async

Please all the way Async, otherwise it will not be controlled.
Network requests, the system comes with Async method does not create multi-threaded file read and write, but the use of completion ports, interrupt rely on to achieve!
Thread in the pool is divided into WorkerThread and CompletionPortThread.
We usually use threads is WorkerThread, IO read and write using CompletionPortThread

1. Create IO-intensive tasks

The following code does not create multiple threads (WorkerThread) , the code will work in the current thread, and will not clog oh.
Very similar to the synchronization procedure performed using await RunActionAsync (() => {
}); after the execution of the program will immediately

public Task RunActionAsync(Action action)
{
    TaskCompletionSource<Task> source = new TaskCompletionSource<Task>(TaskCreationOptions.AttachedToParent);
    Task<Task> task = source.Task;

    try
    {
        action.Invoke();
    }
    catch (Exception ex)
    {
        source.SetException(ex);
    }

    source.SetResult(Task.CompletedTask);

    return task;
}

2. compute-intensive tasks

The following code creates a new thread (WorkerThread) , located in the thread pool, thread pool WorkerThread as default minimum number of CPU cores, CompletionPortThread 1000 (actual minimum depending on the actual operating circumstances, can be manually changed)
and will not be executed immediately runtime Action , according to the default implementation plan (TaskScheduler.Default execution, such as a for loop pile Task.Run (async () => { await httpgetAsync (); echo (i);) task execution you will find i is the last one value

await Task.Run(()=>{});

The following code creates a new thread (WorkerThread) , the key lies in not ThreadPool TaskCreationOptions enumeration, if LongRunning , the immediate task will be to create a thread to perform non-thread pool, if not, it will look for threads in the thread pool, if not We will apply for new threads in the thread pool (to create a time-consuming second), perform the task.
Action will be executed immediately

Task.Factory.StartNew(_ =>
{
    action.Invoke();
},
    null,
    CancellationToken.None,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default)

3. Some pit

The following code does not support .NET Core Oh, instead of using the Task.Factory.StartNew

Task.Factory.FromAsync(
    new Func<AsyncCallback, object, IAsyncResult>((cb, obj) => action.BeginInvoke(biz, cb, obj)),
    new Action<IAsyncResult>(ar => action.EndInvoke(ar)), null)

reference

The danger of TaskCompletionSource class

TaskScheduler and understand .NET default thread pool (ThreadPool) setting, avoid drastically reduced performance Task.Run

.NET carefully nested Task wait, it may run out of available resources you thread pool, similar to the deadlock situation

.NET is used as a thread TaskCompletionSource synchronous or asynchronous operation of exclusive events

Defines a set of abstract Awaiter the implementation of the interface, the next time you write your own await objects can wait will be more convenient

In addition to using Task .NET addition, how to write an object that can await their own?

What kind of .NET classes are available await an asynchronous wait?

Asynchronous I/O in C#: I/O Completion Ports

Asynchronous I/O in C#: I/O Completion Ports

Migrating Delegate.BeginInvoke Calls for .NET Core

statement

This article uses Creative Commons Attribution - NonCommercial - ShareAlike 2.5 license agreement in China to license, issued in CSDN and garden blog , readers are welcome to reprint, but without the author's consent declared by this section must be retained, and in the apparent position of the article page gives the original connection! The reader / reptiles are respected版权

Guess you like

Origin www.cnblogs.com/chasingdreams2017/p/11617985.html