C #, await / async Chatting

Original: C # in await / async Chatting

Since C # 5.0 increase asynchronous programming, asynchronous programming more simple, more and more local async and await use, more and more easy to use, as long as the place is a series of asynchronous induction, if you want to asynchronous programming time, need to start writing from the bottom, so when using the back is asynchronous, so the bottom is how to achieve? ? How do we write efficient asynchronous method? ?

# Understand the task-based asynchronous mode (TAP)

The task of asynchronous programming model (TAP) provides abstraction based on asynchronous code, you will return to your normal code written as a series of statements to run in place to start the call. For example: var task = method () ①; await task②; runs may not run to completion in time ①, ② program hangs waiting to run in the finish, in the middle of you need to know how to run the compiler will do a number of operations . When open multiple tasks, like they should have been performed, in the implementation of the other, may await Task.WhenAll (task1, task2 .....);

# Learn async / await

operator to await asynchronous method, the insertion point of suspension in the execution of the method, the waiting until the task is completed. Defined using async and await an asynchronous method does not necessarily create a new thread, when the compiler sees await keyword, threads hanging waiting for the end of the run.
await only be used to modify the async keyword by the asynchronous method using the method defined async modifiers generally comprise one or more expressions await use await operator tasks are usually achieved [task-based asynchronous mode (the TAP)] method call returns, returns, and methods ValueTask ValueTask <TResult> object includes a Task, Task <TResult> value.

# Sufficient condition for calling Task.Wait () or Task.Result immediate deadlock

1. Call Wait () or Result of code is in the UI thread.
2. Task in the actual execution of other threads, and the need to return to the UI thread.
Cause of a deadlock: UI thread UWP, WPF, Windows Forms program is single-threaded. To avoid deadlocks, you should use one way, Async All the Way. Or .ConfigureAwait (false)

Task of the difference between # ValueTask

7.0 is the role of the new async ValueTask of (if not downloaded System.Threading.Tasks.Extensions on Nuget, ValueTask in this library), ValueTask value for the type of asynchronous; Task is a reference type, and each needs to be allocated space.
E.g:

public async Task<int> CalculateSum(int a, int b) {
    if (a == 0 && b == 0)
    {
        return 0;
    }

    return await Task.Run(() => a + b);
}

When a, b = 0 when the task will not run in this time returns the task and causing waste of resources, the following modifications will be higher efficiency

public async ValueTask<int> CalculateSum2(int a, int b)
{
    if (a == 0 && b == 0)
    {
        return 0;
    }

    return await Task.Run(() => a + b);
}

But not to say that good will everywhere with ValueTask, when a reference type, with ValueTask, you need to focus on more data, this time with the Task better.

# Await / async Principle Analysis

[AsyncStateMachine(typeof(Class1.<CalculateSum2>d__1))]
public ValueTask<int> CalculateSum2(int a, int b)
{
    Class1.<CalculateSum2>d__1 <CalculateSum2>d__;
    <CalculateSum2>d__.a = a;
    <CalculateSum2>d__.b = b;
    <CalculateSum2>d__.<>t__builder = AsyncValueTaskMethodBuilder<int>.Create();
    <CalculateSum2>d__.<>1__state = -1;
    AsyncValueTaskMethodBuilder<int> <>t__builder = <CalculateSum2>d__.<>t__builder;
    <>t__builder.Start<Class1.<CalculateSum2>d__1>(ref <CalculateSum2>d__);
    return <CalculateSum2>d__.<>t__builder.Task;
}

For CalculateSum2 code analysis, we found no await / async, the original is syntactic sugar provided by the compiler.

[__DynamicallyInvokable, DebuggerStepThrough, SecuritySafeCritical]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
    if (stateMachine == null)
    {
        throw new ArgumentNullException("stateMachine");
    }
    ExecutionContextSwitcher executionContextSwitcher = default(ExecutionContextSwitcher);
    RuntimeHelpers.PrepareConstrainedRegions();
    try
    {
        ExecutionContext.EstablishCopyOnWriteScope(ref executionContextSwitcher);
        stateMachine.MoveNext();
    }
    finally
    {
        executionContextSwitcher.Undo();
    }
}

Analysis of the Start method, can be seen running MoveNext, but it is still a program step by step, then await / async will create a thread, This is not necessarily the decision by the thread pool, then the asynchronous does not create a thread , how asynchronous and asynchronous here is probably already on some threads to run.

.NET optimized in parallel development , C #, multi-threaded parallel processing , Multi-threaded C # variables in this article are a few pieces of multithreading in C #, the introduction of different emphases.

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11100203.html