Invoke a synchronous asynchronous method

I need to invoke an asynchronous method synchronously for reasons beyond my control. I am developing a library that uses another library that works asynchronously, and I need to use it from the class implementation Stream. Such a class contains synchronous and asynchronous methods, and I feel awkward in synchronous:

public override sealed int Read(byte[] buffer, int offset, int count)
{ 
    // potential deadlock on single threaded synchronization context
    return ReadAsync(buffer, offset, count).Result;
}

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
   return await _lib.ReadAsync(buffer,offset,count);
}

I read How do I run the task async <T> method synchronously? specifically this answer , and in the comments of @Stephen Cleary states that the solution is not very good, as some parts of ASP.NET are expected AspNetSynchronizationContext. I am developing a library, so I don’t know where my classes will be called from.

?

+3
1

.

, :

  • ; . (, , ).
  • , . , ConfigureAwait(false), , . , Task.Run . , , , Wait Result AggregateException.

.

+3

All Articles