c# - 调试异步等待 Controller 操作

标签 c# asp.net-web-api visual-studio-2015 async-await

我已经在 ApiController 中实现了(我认为是)一个简单的异步方法,如下所示:

public class CommentsController : ApiController
{
    private static readonly IList<CommentModel> Comments;

    static CommentsController()
    {
        // Note: Removed to abbreviate - populate comments manually here.
    }

    [ResponseType(typeof (IList<CommentModel>))]
    [HttpGet]
    public async Task<IHttpActionResult> GetAllComments()
    {
        return await Task.Factory.StartNew(() =>
        {
            Thread.Sleep(10000); // Breakpoint #1
            return Ok(Comments); // Breakpoint #2
        });

        // Breakpoint #3
    }
}

注意我在上面放置的断点。

当我点击继续时,我预计会发生在 #1,线程等待,但流程在此阶段继续通过 #3。

然后当 sleep 结束时,再次继续并在#2 处中断。

但是在调试期间它似乎是同步的。

我的问题首先是这是否真的是异步的,我该如何调试它来验证,或者以其他方式进行单元测试?

最佳答案

However during debugging it seems synchronous.

它是串行的(不是同步的),因为 await 关键字告诉方法在该操作完成之前不要继续。调试器将以串行方式逐步执行异步方法,这可以使它们看起来是同步的;这比让调试器跳转到不相关的代码然后稍后再跳回去要自然得多。

My question is firstly is this truly asynchronous

它是伪异步的。在实际代码中,您永远不会使用 Task.Factory.StarNew

此外,对于 ASP.NET 应用程序,您应该避免将工作发送到线程池(StartNewTask.Run 等)。相反,您应该调用自然异步 API。

how to I debug it to verify, or otherwise with unit tests?

您可以调用该方法,验证任务是否尚未完成,然后等待它。请注意,为避免竞争条件,您应该停止 Controller 正在使用的任何异步服务。

关于c# - 调试异步等待 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36027013/

相关文章:

c# - Entity Framework 6 中的一对多关系

c# - 在函数完成其任务后定期执行函数

asp.net-mvc-4 - 以复杂对象为参数的Web API Get方法

c# - 使用 HttpClient 时避免从异步函数返回类型 Task<Object>

git - 如何在 git 中处理 .csproj

c# - Silverlight 的几何绘图和操作选项

javascript - 在 angularjs 中找不到 url

visual-studio-2015 - Nuget 无缘无故抛出 401 未经授权的错误

c++ - 为什么我收到此错误 : constexpr' is not valid here

c# - 删除表中的特定条目