首页 > 解决方案 > 在 .NET Core 中的 ActionResult 之后调用方法

问题描述

我是 MVC 的新手,所以我的想法可能完全错误,但我想实现当我在控制器中调用一个动作时,一旦它返回结果,就会调用另一个方法。

目前我的代码正在以这种方式工作:

[HttpGet("/api/compile/{*path}")]
public IActionResult Compile(string path)
{
    this.Queue.QueueBackgroundWorkItem(async token =>
    {
        await cp.Compile()
                .ContinueWith((compilation) =>
                    Console.WriteLine(compilation.Result), token);
    });

    return new ContentResult
    {
        Content = "<div>Compilation requested...</div>",
        ContentType = "text/html"
    };
}

它按预期工作,后台作业已入队,并将返回内容结果。

我的问题是,如果我检查控制台日志,当然由于合理的原因,后台作业在返回内容结果之前就开始登录控制台,所以我看到的是:

backgroundjob log...1
backgroundjob log...2
[compilation.Result]
backgroundjob log...3
backgroundjob log...4
...

但我想达到,后台作业将在结果返回后严格排队。

[compilation.Result]
backgroundjob log...1
backgroundjob log...2
backgroundjob log...3
backgroundjob log...4
...

也许我可以Thread.Sleep在后台作业匿名方法中添加一个,但当然这不是一致且逻辑精细的方式,但目前我不知道如何解决这个问题。

谢谢您的帮助!

标签: c#asp.net-core-mvc

解决方案


推荐阅读