Last active
June 3, 2017 23:00
-
-
Save sbolum/5e52c6fdc82ca01d4ed36a18751e9868 to your computer and use it in GitHub Desktop.
Call Async Methods as Sync
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
/// <summary> | |
/// Async metodları sync bir şekilde kullanabilmek için helper. | |
/// </summary> | |
public static class AsyncHelper | |
{ | |
private static readonly TaskFactory _myTaskFactory = new | |
TaskFactory(CancellationToken.None, | |
TaskCreationOptions.None, | |
TaskContinuationOptions.None, | |
TaskScheduler.Default); | |
public static TResult RunSync<TResult>(Func<Task<TResult>> func) | |
{ | |
return AsyncHelper._myTaskFactory | |
.StartNew<Task<TResult>>(func) | |
.Unwrap<TResult>() | |
.GetAwaiter() | |
.GetResult(); | |
} | |
public static void RunSync(Func<Task> func) | |
{ | |
AsyncHelper._myTaskFactory | |
.StartNew<Task>(func) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
} | |
/// <summary> | |
/// Runs a TPL Task fire-and-forget style, the right way - in the | |
/// background, separate from the current thread, with no risk | |
/// of it trying to rejoin the current thread. | |
/// </summary> | |
public static void RunAndForget(Func<Task> fn) | |
{ | |
Task.Run(fn).ConfigureAwait(false); | |
} | |
/// <summary> | |
/// Runs a task fire-and-forget style and notifies the TPL that this | |
/// will not need a Thread to resume on for a long time, or that there | |
/// are multiple gaps in thread use that may be long. | |
/// Use for example when talking to a slow webservice. | |
/// </summary> | |
public static void RunAndForgetLong(Func<Task> fn) | |
{ | |
Task.Factory.StartNew(fn, TaskCreationOptions.LongRunning) | |
.ConfigureAwait(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment