Last active
May 29, 2024 11:56
-
-
Save ctigeek/33d0d458e70581bb1e5a to your computer and use it in GitHub Desktop.
Run an Async Task Synchronously in the thread pool. This will not copy any thread context.
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
private void button2_Click(object sender, EventArgs e) | |
{ | |
try | |
{ | |
//both methods do basically the same thing. | |
//I recommend the first since it's much simpler. | |
var body = RunSynchronouslyInAnotherTask(GetBody); // method 1 | |
//var body = RunSynchronouslyInThreadPool(GetBody); // method 2 | |
this.textBox1.Text = body; | |
} | |
catch (Exception ex) | |
{ | |
this.textBox1.Text = ex.ToString(); | |
} | |
} | |
private T RunSynchronouslyInAnotherTask<T>(Func<Task<T>> taskAction) | |
{ | |
T result = default(T); | |
Task.Run(async () => { result = await taskAction(); }).Wait(); | |
return result; | |
} | |
private T RunSynchronouslyInThreadPool<T>(Func<Task<T>> taskAction) | |
{ | |
using (var semaphore = new SemaphoreSlim(0, 1)) | |
{ | |
T result = default(T); | |
Exception asyncException = null; | |
ThreadPool.QueueUserWorkItem(o => | |
{ | |
try | |
{ | |
var task = taskAction(); | |
result = task.Result; | |
} | |
catch (Exception exception) | |
{ | |
asyncException = exception; | |
} | |
semaphore.Release(); | |
}); | |
semaphore.Wait(); //block until delegate is complete. | |
if (asyncException != null) | |
{ | |
throw asyncException; | |
} | |
return result; | |
} | |
} | |
private async Task<string> GetBody() | |
{ | |
var client = new HttpClient(); | |
//throw new ApplicationException("blah"); | |
var response = await client.GetAsync("http://www.google.com"); | |
var body = await response.Content.ReadAsStringAsync(); | |
return body; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment