Task.Factory.StartNew与Async方法 [英] Task.Factory.StartNew vs Async methods

查看:708
本文介绍了Task.Factory.StartNew与Async方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个琐碎的问题,但这可能对我的基本理解有所帮助.

Might be a trivial question, but it might help me in basic understanding.

以下两个实现之间是否有重要区别?

Is there any important difference between two following implementations?

  1. Task.Factory.StartNew:

public Task<string> ReadAllTextAsync(string path) {
    return Task.Factory.StartNew(() => File.ReadAllText(path));
}

  • StreamReader上的异步方法:

  • Async method on StreamReader:

    public async Task<string> ReadAllTextAsync(string path) {
        using (var stream = File.OpenRead(path))
        using (var reader = new StreamReader(stream)) {
            return await reader.ReadToEndAsync();
        }
    }
    

  • 推荐答案

    是的,有一个关键的区别:Task.Factory.StartNew不保留同步上下文,而在使用async/await时保留此上下文.例如,在ASP.NET应用程序中,这意味着如果使用Task.Factory.StartNew,则在任务内部可能无法访问HttpContext,而如果使用async/await,则它将可用.

    Yes, there's a crucial difference: the Task.Factory.StartNew is not preserving the synchronization context whereas when using async/await this context is preserved. For example in an ASP.NET application this means that if you use Task.Factory.StartNew the HttpContext might not be accessible inside the task whereas if you use async/await it will be available.

    您提供的示例还有另一个重要区别.在第一种情况下,您将使用阻塞API:File.ReadAllText(path),而在第二种情况下,您将使用具有真正异步I/O操作的I/O完成端口.这意味着,在第一种情况下,您将在执行此任务的整个过程中危及该任务执行的线程,而在第二种情况下,由于有I/O完成端口,因此该线程是空闲的.

    There's also another important difference with the example you provided. In the first case you are using a blocking API: File.ReadAllText(path) whereas in the second case you are using an I/O Completion port with a true asynchronous I/O operation. This means that in the first case you are jeopardizing the thread on which this task executes during the entire time this task is executing whereas in the second case this thread is free thanks to an I/O Completion Port.

    这篇关于Task.Factory.StartNew与Async方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆