Implementing JQuery style 'deferred' and 'promise' in C#
I like how you can call Resolve any number of times, but the listening objects will only be notified once. I also like how you can attach a listening object after Resolve has already been called, and the listening object will still get the notification. If you're programming in an uncertain multithreaded environment, it greatly reduces the amount of thinking you have to do.


This sounds a lot like TaskCompletionSource along with the Task it controls.

Assuming you have a TaskCompletionSource&lt;T&gt; tcs:


To attach a listener, use tcs.Task.ContinueWith(_ =&gt; /* listener code here */). You can do this before or after the Task has been completed and the listener code will be executed only once after the Task has been completed.
To complete the Task (the equivalent of resolving), use tcs.TrySetResult(someValue). If you'll use the TrySetResult() variant instead of SetResult(), the second and following attempt at completing will be ignored (SetResult() would throw an exception).


The difference with your code is that TaskCompletionSource always has some result type. You can either just ignore that (using e.g. TaskCompletionSource&lt;object&gt; and SetResult(null)), or use the non-generic TaskCompletionSource from AsyncEx.