Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create async version of sync method

Tags:

c#

async-await

I'm currently writing an component where I already have a synchronous method to download files from a server. Here's the signature:

public Stream DownloadFile(IData data)

Now I wanted to have an async version of this method and tried this:

 public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      DownloadFile(data);
    });
    return stream;
 }

But resharper is showing me a squiggle line under return stream; "expression is always null". Can somebody tell me what is wrong with my code?

What I want to do is run the DownloadFile method in background and return controlflow to the caller.

EDIT: here is the DownloadFile method:

var ms = new MemoryStream();

  using (var dtService = new DataTransferService(mConnectionInfo))
  {
    int bytesRead;
    do
    {
      var buffer = new byte[data.ChunkSize];
      bytesRead = dtService.Read(data, buffer);

      if (bytesRead == 0)
      {
        break;
      }

      data.Offset += bytesRead;
      ms.Write(buffer, 0, buffer.Length);
    } while (bytesRead > 0);
  }


  return ms;

Thanks

like image 983
user3292642 Avatar asked Nov 29 '25 20:11

user3292642


1 Answers

Best option would be to rewrite the DownloadFile() method using async I/O, for instance with HttpClient.

Making the current DownloadFile() async with a wrapper is pointless.
If you are stuck between a requirement and the given infrastructure then just fake it while doing the least amount of damage:

public Task<Stream> DownloadFileAsync(IData data)  // not 'async', just Task<>
{
    return Task.FromResult(DownloadFile(data));
}
like image 84
Henk Holterman Avatar answered Dec 01 '25 10:12

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!