user3292642
user3292642

Reputation: 761

Create async version of sync method

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

Upvotes: 3

Views: 2062

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273774

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));
}

Upvotes: 4

Backs
Backs

Reputation: 24913

Because you return stream variable, and it's null :)

Just return your Task

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

Upvotes: 2

nvoigt
nvoigt

Reputation: 77364

You forgot to actually assign the stream variable:

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

Upvotes: 0

Related Questions