RPM*_*984 3 c# asp.net-mvc asynchronous asynccallback asp.net-mvc-3
我有一个ASP.NET MVC 3动作方法,它接受HttpFileCollectionBaseHTTP POST.
在这种方法中,我需要调整大小并上传图像3次.
动作方法目前如下所示:
public ActionResult ChangeProfilePicture()
{
var fileUpload = Request.Files[0];
ResizeAndUpload(fileUpload.InputStream, Size.Original);
ResizeAndUpload(fileUpload.InputStream, Size.Profile);
ResizeAndUpload(fileUpload.InputStream, Size.Thumb);
return Content("Success", "text/plain");
}
Run Code Online (Sandbox Code Playgroud)
基本上这是一个用户个人资料页面,他们在那里更改他们的个人资料图片 上传通过jQuery AJAX发生.
现在,如何将三个ResizeAndUpload调用作为异步任务触发,但是在完成所有三个任务之前不返回操作结果?
以前我一直Task.Factory.StartNew用来启动异步任务,但那时我并不关心等待结果.
有任何想法吗?
一种简单的方法是使用Join:
public ActionResult ChangeProfilePicture()
{
var fileUpload = Request.Files[0];
var threads = new Thread[3];
threads[0] = new Thread(()=>ResizeAndUpload(fileUpload.InputStream, Size.Original));
threads[1] = new Thread(()=>ResizeAndUpload(fileUpload.InputStream, Size.Profile));
threads[2] = new Thread(()=>ResizeAndUpload(fileUpload.InputStream, Size.Thumb));
threads[0].Start();
threads[1].Start();
threads[2].Start();
threads[0].Join();
threads[1].Join();
threads[2].Join();
return Content("Success", "text/plain");
}
Run Code Online (Sandbox Code Playgroud)
虽然ResizeAndUpload方法可能在某个地方阻塞(但是在没有看到代码的情况下无法确定),但在这种情况下重构它们以使它们异步也是值得的.
也使用它Task.Factory.StartNew,类似于@BBree的答案:
public ActionResult ChangeProfilePicture()
{
var fileUpload = Request.Files[0];
var threads = new Task[3];
threads[0] = Task.Factory.StartNew(()=>ResizeAndUpload(fileUpload.InputStream, Size.Original));
threads[1] = Task.Factory.StartNew(()=>ResizeAndUpload(fileUpload.InputStream, Size.Profile));
threads[2] = Task.Factory.StartNew(()=>ResizeAndUpload(fileUpload.InputStream, Size.Thumb));
Task.WaitAll(threads, 120000); // wait for 2mins.
return Content("Success", "text/plain");
}
Run Code Online (Sandbox Code Playgroud)
现在知道Thread或Task更好.