Answer the question
In order to leave comments, you need to log in
Wrapping Event-based async code in Task-based. Why is it better to use TaskCompletionSource?
There is a service written using the EAP approach, with two methods (synchronous and asynchronous).
We need to wrap it all in TAP. Which option is preferred and why?
1) Task.Factory.StartNew(action, cancellationToken), where the synchronous service method is wrapped in action.
2) Use TaskCompletionSource and wrap the asynchronous method.
Option 1 has already been implemented, because it's faster and easier.
Should it be redone using TaskCompletionSource?
Answer the question
In order to leave comments, you need to log in
TaskCompletionSource is usually worth using when you need to create a Task, but there is no long-running synchronous method we can wrap.
For example,
public Task<bool> StartServiceAsync()
{
// вызываем метод, который отрабатывает быстро,
// но возвращает результат не сразу, а через неопределенное время
// в своем событии _someService.ServiceStarted
_someService.StartAsync();
if (_serviceTcs != null) _serviceTcs.SetCanceled();
_serviceTcs = new TaskCompletionSource<bool>();
return _serviceTcs.Task;
}
private void OnServiceStarted(object sender, bool e)
{
// При срабатывании события от сервиса завершаем ожидающую задачу
if (_serviceTcs != null) _serviceTcs.SetResult(e);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question