Understanding async - can I wait for a synchronous method?

Trying to understand async-awaitin C # and got a little stuck in the chicken and egg problem, maybe.

Can a method asynccall another asyncfor asynchronous?

As a high-level example, I'm trying to make a simple write to the file system, but I'm not sure how I can make this task expected, 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
}

This line of code is called inside the method I'm trying to make asynchronous. Therefore, while the file is being written, I would like to gain control of the application, but I'm not quite sure how to do it.

Can someone enlighten me with a very high example of how I can write a file to a file system with async?

+4
2

?

, async , -. File.WriteAllBytes, . .

- , ?

, API, 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.
}
+6

Yuval : - , Task.Run, :

public Task<FileActionStatus> SaveAsync(path, data)
{
  return Task.Run<FileActionStatus>(() =>
    {
      File.WriteAllBytes(path, data);
      // don't forget to return your FileActionStatus
    });
}

: . , . , , parallelism. , . .

-1

Source: https://habr.com/ru/post/1616860/


All Articles