Created
September 19, 2018 21:53
-
-
Save foobit/1fe4c9a6f8fe6fe8d88329c49b11b612 to your computer and use it in GitHub Desktop.
C# broadcast signaled event via Task completion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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