Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctigeek/33d0d458e70581bb1e5a to your computer and use it in GitHub Desktop.
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.
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