-
-
Notifications
You must be signed in to change notification settings - Fork 255
Description
in bit-framework we've something like this following code
public interface ISomeContract { Task<int> SomeMethodAsync(CancellationToken cancellationToken); int SomeMethod(); }
and suppose this implementation of it's contract
public class SomeImplementation : ISomeContract { public int SomeMethod() { // lots of codes ... return 10; } public async Task<int> SomeMethodAsync(CancellationToken cancellationToken) { return SomeMethod(); // another example: I can remove async modifier from SomeMethodAsync method and this following //try //{ // return Task.FromResult<int>(SomeMethod()); //} //catch (Exception ex) //{ // return Task.FromException<int>(ex); //} } }
we have some options to reuse sync method in async implementation
1)
public Task<int> SomeMethodAsync(CancellationToken cancellationToken) { return Task.Run(() => SomeMethod(), cancellationToken); }
2)
public async Task<int> SomeMethodAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return SomeMethod(); }
3)
public Task<int> SomeMethodAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } try { return Task.FromResult(SomeMethod()); } catch (OperationCanceledException oce) { var canceledTaskBuilder = new TaskCompletionSource<int>(); canceledTaskBuilder.SetCanceled(); return canceledTaskBuilder.Task; } catch (Exception e) { return Task.FromException<int>(e); } }
more detail in this following:
how to reuse sync code