Prevent deadlock by running a task at the same time - Windows Service

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

Here is 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 many ways to run this task in a synchronization function. Here are 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 what is the best solution to run the async method synchronously in syncFoo() without causing deadlocks. Should I do this as in syncFoo2() ?

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

+5
source share
1 answer

Since this is a Windows service, a task should never run synchronously, as suggested by Stephen . I changed it as asynchronous and it works fine.

+2
source

All Articles