了解异步 - 我可以等待同步方法吗? [英] Understanding async - can I await a synchronous method?

查看:195
本文介绍了了解异步 - 我可以等待同步方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在C#中理解 async-await ,并且可能会陷入鸡蛋和鸡蛋问题。

Trying to understand async-await in C#, and a bit stuck in a "chicken and egg" problem, maybe.

async 方法是否需要调用另一个 async 才能使它异步?

Does an async method need to call another async for it to be asynchronous?

作为一个高级示例,我正在尝试对文件系统进行简单的写操作,但不确定如何完成此任务(如果有的话)。

As a high level example, I'm trying to do a simple write to the file system, but not sure how I can make this task awaitable, if at all.

public Task<FileActionStatus> SaveAsync(path, data)
{
    // Do some stuff, then...

    File.WriteAllBytes(path, data); // <-- Allow this to yield control?

    // ... then return result
}

在我试图异步的方法中调用那行代码。因此,在编写文件时,我想对应用程序进行控制,但不太确定如何执行此操作。

That line of code is being called within a method that I'm trying to make asynchronous. So while the file is being written, I'd like to yield control to the application, but not quite sure how to do that.

有人可以用非常好的方式启发我如何以 async 的方式将文件写入文件系统的高级示例?

Can someone enlighten me with a very high-level example of how I could write a file to the file system in an async way?

推荐答案


异步方法是否需要调用另一个异步才能使它异步?

Does an async method need to call another async for it to be asynchronous?

通常就是这种情况,因为async一直到调用堆栈的底部,并在实际进行IO操作的最低位置结束。在您的情况下,您使用 File.WriteAllBytes 这是阻止同步调用。你不能神奇地使它异步。

Usually that is the case as async goes all the way to the bottom of the call-stack and ends at the lowest place which is actually making the IO operation. In your case, you're using File.WriteAllBytes which is a blocking synchronous call. You can't magically make it asynchronous.


有人可以通过一个非常高级的例子来启发我,我可以将文件编写到文件系统是否以异步方式?

Can someone enlighten me with a very high-level example of how I could write a file to the file system in an async way?

为此,您需要使用一种公开异步API的机制,例如< a href =https://msdn.microsoft.com/en-us/library/system.io.filestream(v=vs.110).aspx\"rel =nofollow> FileStream

To do that you need to be using a mechanism which exposes an asynchronous API, such as FileStream:

public async Task<FileActionStatus> SaveAsync(string path, byte[] data) 
{
    using (FileStream sourceStream = new FileStream(path,
    FileMode.Append, FileAccess.Write, FileShare.None,
    bufferSize: 4096, useAsync: true))
    {
        await sourceStream.WriteAsync(data, 0, data.Length);
    }
    // return some result.
}

这篇关于了解异步 - 我可以等待同步方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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