Warme Bakker
Warme Bakker

Reputation: 15

Passing Stream to async method

I'm trying to pass a stream-parameter to an async method, like this:

async void MyAsyncMethod(Stream s, int i)
{
    await Task.Factory.StartNew(() =>
        {
            SomeMethodReadingFromStream(s, i); // throws ArgumentException, "Stream was not readable."
        });
}

When I make MyAsyncMethod not use async-await, all works fine.

Is there a way to use a stream in an async method?

Upvotes: 1

Views: 1903

Answers (1)

dcastro
dcastro

Reputation: 68640

The calling method probably looks like this:

using(var stream = ...)
{
    MyAsyncMethod(stream, 3);
}

Since you're kicking off MyAsyncMethod and then closing the stream, when MyAsyncMethod runs the stream will have been closed.

One way to solve this is to change MyAsyncMethod signature to return a task, and then await it.

async Task MyAsyncMethod(Stream s, int i) { ... }

using(var stream = ...)
{
    await MyAsyncMethod(stream, 3);
}

This way, the stream won't be closed until MyAsyncMethod is done.

Upvotes: 10

Related Questions