Skip to content

Instantly share code, notes, and snippets.

@Warrenn
Created May 3, 2022 07:57
Show Gist options
  • Save Warrenn/666a817019e2797fd45f0b544f8710d4 to your computer and use it in GitHub Desktop.
Save Warrenn/666a817019e2797fd45f0b544f8710d4 to your computer and use it in GitHub Desktop.
facilitates async await
public static class StaticAsyncMediator
{
private static readonly IDictionary<string, object>
CompletionSources = new ConcurrentDictionary<string, object>();
private static TaskCompletionSource<T> GetCreateSource<T>(string key)
{
var fullKey = $"{typeof(T).FullName}:{key}";
if (CompletionSources.ContainsKey(fullKey) && CompletionSources.TryGetValue(fullKey, out var returnValue))
return (TaskCompletionSource<T>) returnValue;
var newTaskCompletion = new TaskCompletionSource<T>(TaskCreationOptions.LongRunning);
CompletionSources.TryAdd(fullKey, newTaskCompletion);
return newTaskCompletion;
}
public static void RegisterResult<T>(T result, string key = "")
{
var source = GetCreateSource<T>(key);
source.SetResult(result);
}
public static async Task<T> GetResultAsync<T>(string key = "")
{
var source = GetCreateSource<T>(key);
return await source.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment