Skip to content

Instantly share code, notes, and snippets.

@foobit
Created September 19, 2018 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foobit/1fe4c9a6f8fe6fe8d88329c49b11b612 to your computer and use it in GitHub Desktop.
Save foobit/1fe4c9a6f8fe6fe8d88329c49b11b612 to your computer and use it in GitHub Desktop.
C# broadcast signaled event via Task completion
using System;
using System.Threading;
using System.Threading.Tasks;
namespace BroadcastEventSample
{
public class EventBroadcastTask
{
private readonly CancellationTokenSource cancelSource = new CancellationTokenSource();
private readonly TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
public EventBroadcastTask()
{
cancelSource.Token.Register(WhenCanceled, tcs);
}
public Task CompletionTask => tcs.Task;
public bool Signaled { get; private set; }
public void Signal()
{
if (!Signaled)
{
Signaled = true;
cancelSource.Cancel();
}
}
private void WhenCanceled(object s)
{
((TaskCompletionSource<bool>)s).SetResult(true);
}
}
class Program
{
static void Main(string[] args)
{
var someEvent = new EventBroadcastTask();
Console.WriteLine("Press ENTER to complete all tasks");
var tasks = new[]
{
Task.Run( async () => { await someEvent.CompletionTask; Console.WriteLine("task 1 complete"); } ),
Task.Run( async () => { await someEvent.CompletionTask; Console.WriteLine("task 2 complete"); } ),
Task.Run( () => { Console.ReadLine(); someEvent.Signal(); })
};
Task.WaitAll(tasks);
Console.WriteLine("all done");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment