一些异步方法为何需要任务的返回类型

一些异步方法为何需要任务的返回类型

本文介绍了一些异步方法为何需要任务的返回类型,和别人不一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此中,该方法有一个返回类型的任务< INT>

实施例1:

 异步任务< INT> AccessTheWebAsync()
{
    //你需要添加一个引用System.Net.Http申报客户端。
    HttpClient的客户端=新的HttpClient();    // GetStringAsync返回任务<字符串取代。这意味着,当你等待
    //任务,你会得到一个字符串(urlContents)。
    任务<串GT; getStringTask = client.GetStringAsync(http://msdn.microsoft.com);    //你可以在这里做的工作,不依赖于从GetStringAsync字符串。
    DoIndependentWork();    //该运营商的await暂停AccessTheWebAsync。
    // - AccessTheWebAsync无法继续下去,直到getStringTask完成。
    // - 同时,控制返回到AccessTheWebAsync的调用者。
    // - 控制,在此继续getStringTask完成时。
    // - 该运营商的await然后检索getStringTask的字符串结果。
    字符串urlContents =等待getStringTask;    // return语句指定一个整数结果。
    //任何正在等待AccessTheWebAsync方法获取长度值。
    返回urlContents.Length;
}

在第二个例子中,它使用异步和等待,但不会返回一个类型任务&LT的;?>为什么

例2:

 命名空间ConsoleApplication
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            ReadCharacters();
        }        静态异步无效ReadCharacters()
        {
            字符串结果;
            使用(StreamReader的读者= File.OpenText(existingfile.txt))
            {
                Console.WriteLine(打开文件);
                结果=等待reader.ReadToEndAsync();
                Console.WriteLine(载:+结果);
            }
        }
    }
}

第三,在第一例中,是有可能返回一个数组(串)?


解决方案

They made an error. Whenever you create a method which is async and doesn't have a return value, it should return a Task. The only exception to that is event handlers, where you need to keep compatibility with the delegates signature, but this isn't the case. Think of a Task as the void equivalent of synchronous methods.

Why do you actually want to return a Task and not void? Because returning a Task allows you to monitor the status of execution, and also lets you to properly handle any exceptions encapsulated inside the on going operation.

For example, think of an async void method that throws:

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

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

When you invoke this, you have no way to actually handle exceptions happening inside the method, it is "fire and forget" for the call-site. But when you expose a Task, you can now better handle that exception by asynchronously waiting:

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

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

Yes, by returning a 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();
    }
}

When you mark a method async, the compiler will implicitly create a Task for you. When you have a return type, the generated task is a Task<T> where T is your return type.

这篇关于一些异步方法为何需要任务的返回类型,和别人不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:31