In one action of my MVC 4 apps, I have a call:
public ActionResult Test()
{
DownloadAsync("uri","file path");
return Content("OK");
}
DownloadAsync
return a Task and I expect to see the DownloadAsync
run in background. But I always see that MVC only response when the Task
of DownloadAsync
is completed (means that need wait for download complete before response). If I wrap the async call in to Task.Run()
or Task.Factory.StartNew()
, then it works as my expectation. Here's method DownloadAsync
:
private Task DownloadAsync(string url, string originalFile)
{
var tsc = new TaskCompletionSource<bool>();
var client = new WebClient();
AsyncCompletedEventHandler completedHandler = null;
completedHandler = (s, e) =>
{
var wc = (WebClient)s;
wc.DownloadFileCompleted -= completedHandler;
if (e.Cancelled)
{
tsc.TrySetCanceled();
}
else if (e.Error != null)
{
tsc.TrySetException(e.Error);
}
else
{
tsc.SetResult(true);
}
wc.Dispose();
};
client.DownloadFileCompleted += completedHandler;
client.DownloadFileAsync(new Uri(url), originalFile);
return tsc.Task;
}
So my question are:
Why MVC request need wait for complete Task in this case? Is there any special for
Task
created byTaskCompletionSource<T>
?How to make the
Task
ofDownloadAsync
run in background without pause the response of MVC request?
Thanks,