Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Run an Async Task Synchronously in the thread pool. This will not copy any thread context.
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
You can’t perform that action at this time.