use*_*202 8 c# async-await async-ctp asp.net-mvc-4 asp.net-web-api
我从这个博客获得的ASP.NET MVC 4 WEB API Controller中有这个异步方法:http: //www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload -with-ASP净的WebAPI /
public async Task<IList<RecivedFile>> Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
var uploadedFiles = newFiles.Select(i =>
{
var fi = new FileInfo(i);
return new RecivedFile(fi.Name, fi.FullName, fi.Length);
}).ToList();
result.AddRange(uploadedFiles);
}
catch (Exception e)
{
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么这个方法确实有一个返回类型的任务?它还不清楚"在哪里"或"向谁"返回此任务?这就像没有人等待/接收返回的对象.
我想知道如果我像这样返回void会有什么影响:
编辑:
我已经尝试了下面的代码,它完全打破了程序.就像运行时失去了对代码的引用一样,代码本身也没有完成运行.
public async void Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
}
catch (Exception e)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET运行时等待它.您可能会发现此视频很有用.
async
假设UI上下文的大多数示例.ASP.NET 还提供了一个上下文,但它是一个"请求"上下文 - 每个HTTP请求一个上下文.我async
/ await
帖子概述了这个"背景",async
/ await
FAQ更详细.