【发布时间】:2015-04-04 04:55:26
【问题描述】:
我一直在试验一些需要在地方重构的旧代码,并通过异步上传文件(服务器端)测试是否对 iis 线程等有任何改进。使用jQuery文件上传客户端。
原代码
[HttpPost]
public ActionResult UploadDocument( HttpPostedFileBase uploadedFile ) {
// Do any validation here
// Read bytes from http input stream into fileData
Byte[] fileData;
using ( BinaryReader binaryReader =
new BinaryReader( uploadedFile.InputStream ) ) {
fileData = binaryReader.ReadBytes( uploadedFile.ContentLength );
}
// Create a new Postgres bytea File Blob ** NOT Async **
_fileService.CreateFile( fileData );
return Json(
new {
ReturnStatus = "SUCCESS" // Or whatever
}
);
}
新代码
[HttpPost]
public async Task<ActionResult> UploadDocumentAsync( HttpPostedFileBase uploadedFile ) {
// Do any validation here
// Read bytes from http input stream into fileData
Byte[] fileData = new Byte[uploadedFile.ContentLength];
await uploadedFile.InputStream.ReadAsync( fileData, 0, uploadedFile.ContentLength );
// Create a new Postgres bytea File Blob ** NOT Async **
_fileService.CreateFile( fileData );
return Json(
new {
ReturnStatus = "SUCCESS" // Or whatever
}
);
}
新方法似乎可以正常工作,但我的问题是:
下面的代码是正确的(最好的)方法吗?这样做有什么问题吗?那里有很多相互矛盾和过时的信息。关于实际这样做是否有任何改进或意义,似乎也有很多争论。是的,它将线程返回给 iis 等,但值得进行开销类型的辩论。
有问题的代码
// Read bytes from http input stream into fileData
Byte[] fileData = new Byte[uploadedFile.ContentLength];
await uploadedFile.InputStream.ReadAsync( fileData, 0, uploadedFile.ContentLength );
【问题讨论】:
-
async /await 是我认为的摇尾巴。希望看到一些证明我错了的论点。这是一个很好的问题。因此,它几乎肯定会被某些交叉守卫管理员删除。
-
你为什么不让 CreateFile 也异步?这是一个测试问题,看看你是否有一个特定的常见误解。同时,我想向您推荐我对这个主题的处理:stackoverflow.com/a/25087273/122718 和 stackoverflow.com/a/12796711/122718。
-
usr 我可能会,但这并不是我真正要问的。尽管在该主题上,关于快速本地数据库访问是否更快保持同步存在很多争论。
标签: c# multithreading asynchronous async-await .net-4.5