Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC 中的异步方法

2024年08月12日57bonelee

我想创建一个async方法,它会开启一个线程,并完成几个相对独立于当前http请求的任务(例如,发送邮件和生成文件,这些都需要时间)

我创建了以下方法

private static async Task<T> DoSeparateTask<T>(Func<T> func) 
{ 
    return func(); 
} 

并想以这样的方式使用它:

private static void DoSomething() 
{ 
    #step 1 - some code for immediate processing 
    #step 2 - some code for generating documents which takes time 
    var additionalDocumentGenerationWork = DoSeparateTask<Document>(() =>{ 
        #additional code for generating Document 
       #even though it returns Document, but 99% time it wont be used in this method 
    }); 
    #step 3 - some code for sending SMTP email which takes time 
    var additionalDocumentGenerationWork = DoSeparateTask<bool>(() =>{ 
        #additional code for sending email 
        return true; 
    }); 
 
} 

一切都会编译,但是当我运行 Web 应用程序时,它仍然会继续加载并等待一切完成,然后再呈现网页。由于 2 个附加任务(电子邮件和文档)与显示网页无关,我如何通过使用异步修饰符来实现这一点?

或者我对async的理解有误...请大家帮我改正...

非常感谢。

请您参考如下方法:

Or if my understanding of async is wrong... please help me to correct...

正如我在我的博客上解释的那样,async does not change the HTTP protocol .在一天结束时,您对每个请求只有一个响应。换句话说,async 屈服于线程池,而不是客户端。

您正在寻找一种在请求/响应生命周期之外执行操作的方法,ASP.NET 不直接支持这种方法。我描述了一些方法 on my blog .最好(最可靠)的方法是将工作放入队列,并有一个独立的后端来处理队列(例如 Azure worker 角色)。