Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Last active May 9, 2019 20:54
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 leandrosilva/99bdd099783d47ea86962f8830d09a82 to your computer and use it in GitHub Desktop.
Save leandrosilva/99bdd099783d47ea86962f8830d09a82 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CodeZone.Helpers.Async
{
public static class TaskHelper
{
public static Task<T> StartSTATask<T>(Func<T> func)
{
var taskCompletionSource = new TaskCompletionSource<T>();
var thread = new Thread(() =>
{
try
{
taskCompletionSource.SetResult(func());
}
catch (Exception e)
{
taskCompletionSource.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return taskCompletionSource.Task;
}
public static Task StartSTATask(Action act)
{
return StartSTATask(() =>
{
act();
return true;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment