C# basics review Async return type

黄舟
Release: 2017-02-07 15:08:48
Original
1882 people have browsed it

Preface


The blogger simply counted the asynchronous articles he has published, and there have been 8 articles intermittently. This time I want to take the return type of async as an example. Talk alone.

Asynchronous methods have three possible return types: Task, Task, and void.

When to use which return type? The specific situation requires specific analysis. If used improperly, the execution result of the program may not be what you want. Let's talk about how to choose different return types for different situations.

Task

[Remember] When you add the async keyword, you need to return an object that will be used for subsequent operations, please use Task.

Task The return type can be used for certain asynchronous methods where the operand has type TResult.

In the following example, the GetDateTimeAsync asynchronous method contains a return statement that returns the current time. Therefore, the method declaration must specify Task.

async Task<DateTime> GetDateTimeAsync()
{
    //Task.FromResult 是一个占位符,类型为 DateTime
    return await Task.FromResult(DateTime.Now);
}
Copy after login

Call the GetDateTimeAsync method:

async Task CallAsync()
{
    //在另一个异步方法的调用方式
    DateTime now = await GetDateTimeAsync();
}
Copy after login

When GetDateTimeAsync is called from an await expression, the await expression retrieves the DateTime type value stored in the task returned by GetDateTimeAsync.

async Task CallAsync()
{
    //在另一个异步方法的调用方式
    //DateTime now = await GetDateTimeAsync();
    //换种方式调用
    Task<DateTime> t = GetDateTimeAsync();
    DateTime now = await t;
}
Copy after login

The GetDateTimeAsync method is called through the CallAsync method, and the call to the non-immediate waiting method GetDateTimeAsync returns Task. The task is assigned to the Task variable of the DateTime in the example. Because the DateTime's Task variable is Task, it belongs to the DateTime property containing type TResult. In this case, TResult represents the date type. When await is applied to a Task, the await expression evaluates to the contents of the Task's DateTime property. At the same time, the value is assigned to the now variable.

This time I demonstrate different variables, you can compare the results yourself:

async Task CallAsync()
{
    //在另一个异步方法的调用方式
    DateTime now = await GetDateTimeAsync();
    //换种方式调用
    Task<DateTime> t = GetDateTimeAsync();
    DateTime now2 = await t;
   //输出的结果对比
    Console.WriteLine($"now: {now}");
    Console.WriteLine($"now2: {now2}");
    Console.WriteLine($"t.Result: {t.Result}");
}
Copy after login

[Note] The Result attribute is a locked attribute. If you try to access it before its task is completed, the currently active thread will be blocked until the task completes and the value is available. In most cases, you should access the property value by using await rather than accessing the property directly.

Task

Asynchronous methods that do not contain a return statement or contain a return statement that does not return an operand usually have a return type of Task. If written to run asynchronously, these methods will be void-returning methods. If you use the Task return type in an asynchronous method, the calling method can use the await operator to pause the caller's completion until the called asynchronous method completes.

See example:

async Task DelayAsync()
{
    //Task.Delay 是一个占位符,用于假设方法正处于工作状态。
    await Task.Delay(100);
    Console.WriteLine("OK!");
}
Copy after login

Call and await the DelayAsync method by using an await statement instead of an await expression, similar to the call statement for a method that returns void. The application of the await operator does not produce a value in this case.

See the example of calling DelayAsync.

//调用和等待方法在同一声明中
await DelayAsync();
Copy after login

Now, I use a method that separates calling and waiting:

//分离
Task delayTask = DelayAsync();
await delayTask;        
void
Copy after login

void return type is mainly used in event handlers, where void return type is required. The void return type can also be used as an alternative to methods that return void, or for methods that perform activities that can be classified as call-and-forget activities. However, you should return Task whenever possible because you cannot await asynchronous methods that return void. Any caller of such a method can only proceed to completion without waiting for the called asynchronous method to complete, and the caller must be independent of any values ​​or exceptions generated by the asynchronous method.

Callers of an asynchronous method that returns void cannot catch exceptions thrown from the method, and such unhandled exceptions may cause application failures. If an exception occurs in an asynchronous method that returns a Task or Task, the exception will be stored in the returned task and raised again while waiting for that task. Therefore, make sure that any asynchronous methods that can raise exceptions have a return type of Task or Task, and that calls to these methods are awaited.

Now, exceptions can also use await, please move here "Looking back at the past and present of C# - Witness the new syntax features of C# 6.0".

void return value example:

private async void button1_Click(object sender, EventArgs e)
{
    //启动进程并等待完成
    await Task.Delay(100);
}
Copy after login

The above is the C# basic review of the return type of Async. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!