V
V
Vadim Ivanenko2016-03-24 22:32:42
.NET
Vadim Ivanenko, 2016-03-24 22:32:42

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

1 answer(s)
I
Igor Valyansky, 2016-03-26
@supra7sky

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);
}

In your case, most likely, the implementation through TaskCompletionSource will be an extra complication

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question