billybob billybob - 1 month ago 18
C# Question

Prevent deadlock by running a Task synchronously - Windows Service

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()
.

Answer

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.