Created
May 3, 2022 07:57
-
-
Save Warrenn/666a817019e2797fd45f0b544f8710d4 to your computer and use it in GitHub Desktop.
facilitates async await
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
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