gpt4 book ai didi

c# - 为什么有些异步方法需要返回类型为 Task,而有些则不需要

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:41 25 4
gpt4 key购买 nike

在此example来自 Microsoft,该方法的返回类型为 Task<int>

示例 1:

async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();

// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();

// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;

// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}

在第二个例子中,它使用了 async 和 await,但没有返回 Task<> 类型,为什么?

示例 2:

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
ReadCharacters();
}

static async void ReadCharacters()
{
String result;
using (StreamReader reader = File.OpenText("existingfile.txt"))
{
Console.WriteLine("Opened file.");
result = await reader.ReadToEndAsync();
Console.WriteLine("Contains: " + result);
}
}
}
}

第三,在第一个例子中,是否可以返回一个数组(字符串)?

最佳答案

In this second example, it uses async and await, BUT doesn't return a type of Task<>, why?

他们犯了一个错误。每当您创建异步且没有返回值 的方法时,它应该返回一个Task。 .唯一的异常(exception)是事件处理程序,您需要在其中保持与委托(delegate)签名的兼容性,但事实并非如此。想想 Task作为void等同于异步方法。

为什么你实际上想要返回一个Task而不是 void ?因为返回一个 Task允许您监视执行状态,还允许您正确处理封装在正在进行的操作中的任何异常。

例如,考虑一个 async void抛出的方法:

public async void WaitAndThrowAsync()
{
await Task.Delay(1000);
throw new Exception("yay");
}

public void CallWaitAndThrowAsync()
{
// What happens when it throws here?
WaitAndThrowAsync();
}

当您调用它时,您无法实际处理方法内部发生的异常,对于调用站点来说它是“即发即忘”。但是当你公开一个 Task ,您现在可以通过异步等待更好地处理该异常:

public async Task WaitAndThrowAsync()
{
await Task.Delay(1000);
throw new Exception("yay");
}

public async Task CallWaitAndThrowAsync()
{
try
{
await WaitAndThrowAsync();
}
catch (Exception e)
{
// Do something.
}
}

Third, in the first example, is it possible to return an array(strings)?

是的,通过返回 Task<string[]> :

public async Task<string> GetArrayAsync()
{
HttpClient client = new HttpClient();
var responseStream = await client.GetStreamAsync("http://msdn.microsoft.com");

using (var streamReader = new StreamReader(responseStream))
{
return await streamReader.ReadToEndAsync();
}
}

当你标记一个方法时 async ,编译器将隐式创建一个 Task为你。当您有返回类型时,生成的任务是 Task<T>其中 T是你的返回类型。

关于c# - 为什么有些异步方法需要返回类型为 Task,而有些则不需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31114848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com