简体   繁体   中英

Call a controller action asynchronously in MVC

I have a Controller in my MVC 5 application as follows;

public class DownloadController : Controller
{
    public FileContentResult CsvDownload(string fileName)
    {
        byte[] data = GetCSVData(fileName);
        return File(data, "text/csv", fileName);
    }
}

I have some other Actions in the DownloadController as well. I want to convert the CsvDownload File result to an async Task, because sometimes the data can take time to process. How can I run the CsvDownload function asynchronously so that it does not block the main thread. At times it takes about 2 to 4 minutes to download data.

What is the preferred solution to running a method on a separate thread while in the same controller.

EDIT

I was searching for a solution when I came across the following: http://blog.newslacker.net/2013/03/aspnet-mvc-how-to-make-working-progress.html

If I can get a solution of something like the following:

public delegate string GetCsvDataCaller(string fileName);
public string GetCsvData(string fileName)
{
    string file = "filename.csv";
    //Get CSV Data
    return file;
}
public JsonResult StartExporting(string fileName)
{            
    var caller = new GetCsvDataCaller(GetCsvData);
    caller.BeginInvoke(fileName, GetCsvCallBack, null);

    return Json(new { Status = "started" }, JsonRequestBehavior.DenyGet);
}
public JsonResult GetCsvCallBack(IAsyncResult ar)
{
    AsyncResult result = (AsyncResult) ar;
    AsyncMethodCaller caller = (AsyncMethodCaller) result.AsyncDelegate;
    string returnValue = caller.EndInvoke();
   return Json(new { FileName = returnValue }, JsonRequestBehavior.DenyGet);
}

Is this possible in ASP.NET MVC?

public class DownloadController : Controller
{
 [HttpPost]
 public async Task<ActionResult> CsvDownload(string fileName)
 {
       byte[] data = await Task.Run(() => GetCSVData(fileName));
        return File(data, "text/csv", fileName);
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM