Kevin Kalitowski Kevin Kalitowski - 1 year ago 171
C# Question

Non-Generic TaskCompletionSource or alternative

I'm working with an alert window (Telerik WPF) that is normally displayed asynchronously ( code continues running while it is open) and I want to make it synchronous by using async/await.

I have this working with

but that class is generic and returns an object like
when all I want is a plain
with no return value.

public Task<bool> ShowAlert(object message, string windowTitle)
var dialogParameters = new DialogParameters { Content = message };

var tcs = new TaskCompletionSource<bool>();
dialogParameters.Closed += (s, e) => tcs.TrySetResult(true);


return tcs.Task;

The code that calls that method is

await MessageBoxService.ShowAlert("The alert text.")

How can I return a non-generic Task that functions similarly which I can await until the
event fires? I understand that I could just ignore the
that is being returned in this code. I am looking for a different solution than that.

Answer Source

The method can be changed to:

public Task ShowAlert(object message, string windowTitle)

Task<bool> inherits from Task so you can return Task<bool> while only exposing Task to the caller


I found a Microsoft document,, by Stephen Toub titled 'The Task-based Asynchronous pattern' and it has the following excerpt that recommends this same pattern.

There is no non-generic counterpart to TaskCompletionSource<TResult>. However, Task<TResult> derives from Task, and thus the generic TaskCompletionSource<TResult> can be used for I/O-bound methods that simply return a Task by utilizing a source with a dummy TResult (Boolean is a good default choice, and if a developer is concerned about a consumer of the Task downcasting it to a Task<TResult>, a private TResult type may be used)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download