gpt4 book ai didi

c# - 异步在异步 Controller mvc 4.0 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:37 24 4
gpt4 key购买 nike

我有一个目标为 targetFramework="4.5"的 MVC 4.0 应用程序。

我基本上必须将现有的文件处理功能从同步转换为异步(这样对于大文件用户就不必等待其他任务)。

我的代码是

[HttpPost]
public async Task<ActionResult> FileUpload(HttpPostedFileBase fileUpload)
{

Coreservice objVDS = new Coreservice ();

//validate the contents of the file
model =objVDS. ValidateFileContents(fileUpload);

// if file is valid start processing asynchronously
await Task.Factory.StartNew(() => { objVDS.ProcessValidFile(model); }, CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.FromCurrentSynchronizationContext());

return view();


}

基本上我想调用一个异步方法,它在服务中执行数据库操作(不同的项目)。

我希望异步进程能够访问服务方法中的上下文。这就是我使用的原因Task.Factory.StartNew() 中的 TaskScheduler.FromCurrentSynchronizationContext()

服务方法如下所示,根据文件类型,调用第二个服务进行数据操作

public async task ProcessValidFile(fileProcessDataModel model)
{
employeeWorkedDataservice service =new employeeWorkedDataservice()

await Task.Factory.StartNew(() =>
{
service .ProcessEmployeeDataFile(model.DataSetToProcess, OriginalFileName, this, model.Source);
},
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.FromCurrentSynchronizationContext());

}

ProcessEmployeeDataFile 返回 void 及其非异步方法。当上面的代码被执行时,它不会返回到 Controller ,直到它完成数据处理。我想我在这里遗漏了一些东西。请指导我解决问题。

谢谢,阿莫尔

最佳答案

看来您误解了 await 的工作原理。

阅读此 https://msdn.microsoft.com/en-us/library/hh191443.aspx#BKMK_WhatHappensUnderstandinganAsyncMethod

在任务中设置一些运行将允许它异步运行,这样您就可以在它运行时做其他事情。

当你需要结果继续时,你使用await关键字。

通过立即await创建任务,您会立即阻塞直到任务完成;使其有效同步。

如果您乐于在不等待处理完成的情况下返回您的 View ,我认为您根本不需要 await,因为您根本不想等待结果的操作。

public task ProcessValidFile(fileProcessDataModel model)
{
employeeWorkedDataservice service =new employeeWorkedDataservice()

return Task.Factory.StartNew(() =>
{
service.ProcessEmployeeDataFile(model.DataSetToProcess, OriginalFileName, this, model.Source);
},
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.FromCurrentSynchronizationContext());
}

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase fileUpload)
{

Coreservice objVDS = new Coreservice ();

//validate the contents of the file
model =objVDS. ValidateFileContents(fileUpload);

// if file is valid start processing asynchronously
// This returns a task, but if we're not interested in waiting
// for its results, we can ignore it.
objVDS.ProcessValidFile(model);

return view();
}

关于您的评论:

我会认真考虑将您的 Controller 传递给您的服务,或者让您的服务依赖于 session 和上下文,因为您将业务逻辑与 API Controller 紧密耦合。

当你在 Controller 中时,从 Controller 中获取你需要的位,并将它们传递给你的服务。

关于c# - 异步在异步 Controller mvc 4.0 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28231404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com