异步标记的同步方法的返回类型

问题描述 投票:0回答:1

我正在尝试理解 C# 中的一些内容。 我了解到 C# 中的异步标记方法必须返回一个任务。 但我还了解到,标记为异步的方法不一定具有异步行为。有时我将方法标记为异步只是为了能够等待方法,即同步执行。这是一个例子:

async Task<int> X()
{
    // Some asynchronous work that returns an int.
    int result = await SomeAsyncOperation();
    return result;
}

在这里,显然,从调用者的角度来看,我可以看着 X 并说,我不需要等待这个方法,因为它是同步的。我知道它会等待

SomeAsyncOperation
的异步执行,只有完成后,它才会给我结果。所以本质上,我将 X 视为同步方法。

但是X仍然需要返回一个Task,它“代表一个可以返回值的异步操作”。我如何在对方法 X 的所有调用中退出此任务链,或者我现在必须将任务拖到对 X 的所有调用中吗?

c# asynchronous async-await task
1个回答
0
投票

来自 Microsoft 文档 for Task :“Task 类表示不返回值并且通常异步执行的单个操作”。

如果您尝试签名

public async int X()
,那么与您遇到的错误相匹配,这将使您能够使用此任务链

public async int X()//  => Compiler Error : CS1983
{
    int result = await SomeOperationAsync(); // 'await' = give me that T from Task<T>
    return result;
}

public Task<int> SomeOperationAsync()
{
    return Task.Run(() =>
    {
        Thread.Sleep(1_000);
        return 1;
    });
}

/* CS1983 : The return type of an async method must be
    - void, 
    - Task
    - Task<T>
    - a task-like type
    - IAsyncEnumerable<T>
    - IAsyncEnumerator<T>
*/

如果返回 void,则会停止任务链,但这很好,因为“任务类代表不返回值的单个操作”

停止任务链示例:

public async void X()
{
    int result = await SomeOperationAsync(); 
    return result;
}
public Task<int> SomeOperationAsync()
{
    return Task.Run(() =>
    {
        Thread.Sleep(1_000);
        return 1;
    });
}
// [...]

public void AnyMethod(){
   Test.X(); //=> run in background
   // Be carefull to not stop the programm until it's finish, otherwise it will be stop abruptly !
}

© www.soinside.com 2019 - 2024. All rights reserved.