Home Backend Development C#.Net Tutorial C# basics review Async return type

C# basics review Async return type

Feb 07, 2017 pm 03:08 PM
async c# type

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)!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

See all articles