1

I have a sync method that calls an async method that returns a Stream.

The async method makes a call to web api and returns a stream that represents a document.

Whenever I call the async method from within my sync method, the stream is returned as closed.

If I call the async method from within another async method, the stream is returned opened.

I can't call the async method from within another async method because I have to implement an interface from an external library and the code that calls the async method is done from within a sync method that's defined in the interface.

So - SyncMethod -> AsyncMethod -> WebApi returns a closed stream

AsyncMethod1 -> AsyncMethod -> WebApi returns an open stream.

Here is the signature for my async method -

public async Task<Response<Stream>> GetSomeDocument()

In my sync method, I call the async method like so -

var task = this.someClass.GetSomeDocument();

task.Wait();

This is where it blows up and throws ObjectDisposedException -

var memoryStream = new MemoryStream();

task.Result.CopyTo(memoryStream);

Any idea why this works if I call my async method from within an async method using await, but calling it from a sync method doesn't?

Thanks.

Chris
  • 2,148
  • 8
  • 31
  • 52
  • Is there any chance you can show us the -> *Async Method* -> that you want to wrap in Sync call? The problem you're facing is not from your side.. It depends on the implementation of *AsyncMethod*. – vendettamit Aug 18 '15 at 18:46
  • Btw - this solution using the AsyncHelpers class worked but I was wondering if there is a newer solution that involves less code - http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously?rq=1 – Chris Aug 18 '15 at 18:49
  • Post all code that operates on the stream in question – usr Aug 18 '15 at 19:17
  • @Chris there could be an option if you are allowed to change the code of *AsyncMethod*. The reason that Asynchelper if working is because it's using a new SynchronizationContext over Current one. Same can be achieved by using **ConfigureAwait(false)** in *AsyncMethod* where it is creating the Task. – vendettamit Aug 18 '15 at 19:23
  • This is a console application, right? – Paulo Morgado Aug 19 '15 at 19:16
  • Are you calling `Dispose` on any stream or using the `using` statement? It would be better if you posted a small and complete code sample that we could test. – Paulo Morgado Aug 19 '15 at 19:17

0 Answers0