deadlock even after using ConfigureAwait(false) in Asp.Net flow

后端 未结 3 1317
无人及你
无人及你 2020-12-20 12:29

I\'m hitting deadlock even after using ConfigureAwait(false), below is the sample code.

As per the sample http://blog.stephencleary.com/2012/02/async-a

3条回答
  •  無奈伤痛
    2020-12-20 13:12

    It blocks when used in ProjectsRetriever because:

    public class ProjectsRetriever
    {
        public string GetProjects()
        {
            //querying the result blocks the thread and wait for result.
            var projects = this.GetProjects(uri).Result;
            ... //require Thread1 to continue.
            ...
        }
    
        private async Task> GetProjects(Uri uri)
        {
            //any thread can continue the method to return result because we use ConfigureAwait(false)
            return await this.projectSystem.GetProjects(uri, Constants.UserName).ConfigureAwait(false);
        }
    }
    
    public class ProjectSystem
    {
        public async Task> GetProjects(Uri uri, string userName)
        {
            var projectClient = this.GetHttpClient(uri);
            var projects = await projectClient.GetProjects();
            // code here is never hit because it requires Thread1 to continue its execution
            // but Thread1 is blocked in var projects = this.GetProjects(uri).Result;
            ...
    }
    

    It does not block when used in ProjectSystem because:

    public class ProjectsRetriever
    {
        public string GetProjects()
        {
            ...
            var projects = this.GetProjects(uri).Result;
            ...//requires Thread1 to continue
            ...
        }
    
        private async Task> GetProjects(Uri uri)
        {
            //requires Thread1 to continue
            return await this.projectSystem.GetProjects(uri, Constants.UserName);
        }
    }
    
    public class ProjectSystem
    {
        public async Task> GetProjects(Uri uri, string userName)
        {
            var projectClient = this.GetHttpClient(uri);
            var projects = await projectClient.GetProjects().ConfigureAwait(false);
            // no deadlock, resumes in a new thread. After this function returns, Thread1 could continue to run
    }
    

提交回复
热议问题