Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent deadlock by running a Task synchronously - Windows Service

Tags:

c#

task

I read that sometimes that calling directly a Task can lead to a deadlock of the main thread.

Here's my async method:

public async Task<List<JobsWithSchedules>> fillJobsAsync()
{
    IOlapJobAccess jobAccess = new OlapJobAccess(_proxy, CentralPointPath);
    List<OlapJob> jobs = await jobAccess.GetAllJobsAsync();
    List<JobsWithSchedules> quartzJobs = null;
    if (jobs != null)
    {
        quartzJobs = fillQuartzJobs(jobs);
    }
    return quartzJobs;
}

I tried a lot of ways to run this task in a sync function. Here's some examples:

public void syncFoo1()
{
    var fillJobsTask = fillJobsAsync().ContinueWith((task) =>
    {
        if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
        {
            List<JobsWithSchedules> quartzJobs = task.Result;
            //...
        }
        else
        {
            //...
        }
    });
    fillJobsTask.Wait();
}

public void syncFoo2()
{
    Task.Run(() => fillJobsAsync()).ContinueWith((task) =>
    {
        if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
        {
            List<JobsWithSchedules> quartzJobs = task.Result;
            //...
        }
        else
        {
            //...
        }
    });
}

I want to know which is better solution to run the async method synchronously in the syncFoo() without causing deadlocks. Should I do it like in syncFoo2()?

PS: syncFoo() is called from a a windows service onStart() and onStop().

like image 417
billybob Avatar asked Jul 21 '15 15:07

billybob


1 Answers

Since it's in a Windows service, the task should never run synchronously as Stephen suggested. I changed it to be async and it's working fine.

like image 101
billybob Avatar answered Nov 17 '22 22:11

billybob