本文介绍了试图理解“共同"的意思.与ASP.NET和HttpClient()的异步死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到常见"异步死锁并从异步最佳实践我尝试在ASP.NET中模拟该问题,以弄清楚为什么我们以前从未遇到过该问题.似乎不同之处在于,以前我们使用http客户端获取异步方法,但这并没有引起问题.

After running into a "common" async deadlock and getting further understanding from Async Best Practices I tried simulating the issue in ASP.NET in an attempt to figure out why we have never ran into this issue before. The difference it seems is the fact that previously we are using the http client get async methods and that hasn't caused an issue.

    public class DeadLockController : ApiController
    {
        /// <summary>
        /// Does not result in deadlock - but why?
        /// </summary>
        [HttpGet]
        public IHttpActionResult HttpDeadLock()
        {
            var client = new HttpClient();
            return Ok( client.GetStringAsync( "https://www.google.com/" ).Result );
        }

        /// <summary>
        /// Results in expected repeatable deadlock.
        /// </summary>
        [HttpGet]
        public IHttpActionResult DeadLock()
        {
            var delayTask = DelayAsync().Result;

            return Ok( delayTask );
        }

        /// <summary>
        /// Does not result in deadlock.
        /// </summary>
        [HttpGet]
        public async Task< IHttpActionResult > FixedDeadLock()
        {
            var delayTask = await DelayAsync();

            return Ok( delayTask );
        }

        private async Task< int > DelayAsync()
        {
           await Task.Delay( 1000 );
           return 0;
        }
    }

因此,如果要调用api/DeadLock/DeadLock,则会遇到本文所述的常见死锁.这是预期/理解的. api/DeadLock/FixedDeadLock是解决此问题的正确"方法.

So if you were to make a call to api/DeadLock/DeadLock you would run into the common deadlock as described in the article. This is expected/understood. api/DeadLock/FixedDeadLock is the "correct" way of getting around this.

尽管拨打电话 api/DeadLock/HttpDeadLock 并不会导致死锁,即使它们在概念上相同并且我不确定为什么? HttpClient不会碰到这个问题吗?理论上,Httpclient在内部进行等待.

However making a call to api/DeadLock/HttpDeadLock doesn't result in a dead lock even though they are conceptually the same and I'm not sure why? Why does HttpClient not run into this issue? theoretically Httpclient is doing a await internally.

推荐答案

api/DeadLock/HttpDeadLock不会死锁的原因是因为在该代码中您没有等待任何任务.

The reason why api/DeadLock/HttpDeadLock is not dead-locking is because within that code you are not awaiting for any task.

您通过调用Task.Result同步等待任务来阻塞线程.

You are instead blocking the thread by synchronosuly waiting on the task by calling Task.Result.

实现这种模式时,死锁通常是异步等待和Task.Wait/Task.Result组合的组合.

Dead-locks when implementing this sort of patterns usually come up with a combination of async-await and Task.Wait/Task.Result combination.

这篇关于试图理解“共同"的意思.与ASP.NET和HttpClient()的异步死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 01:51