Running a longProcess() method in one of my C# api and while doing that we want to wait for that task to complete. But same time don't want to block the UI. I saw many SO threads, but nothing helps in my case. Below, Method 1 does not block UI and Method 2, blocks/freezes UI. Any thoughts?
public class MyApiManager
{
private string _x;
public MyApiManager(string x)
{
_x = x;
}
public void DoProcess()
{
// Method 1: Does NOT block UI, but does not wait either
Task task = Task.Factory.StartNew(() =>
{
Task longProcess = Task.Factory.StartNew(new Action(longProcess));
});
task.Wait();
// Method 2: BLOCKS UI, also waits
//var context = TaskScheduler.FromCurrentSynchronizationContext();
//Task task = Task.Factory.StartNew(() =>
//{
// var token = Task.Factory.CancellationToken;
// Task.Factory.StartNew(() =>
// {
// longProcess();
// }, token, TaskCreationOptions.None, context);
//});
//task.Wait();
}
private void longProcess()
{
// simulate long process
Thread.Sleep(10000);
}
}