Bar*_*mey 7 .net ihttphandler async-await parse-platform
我陷入了异步死锁,我无法找出正确的语法来解决它.我已经看了几个不同的解决方案,但似乎无法弄清楚导致问题的原因.
我使用Parse作为后端并尝试使用处理程序写入表.我的处理程序看起来像:
public class VisitorSignupHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//Get the user's name and email address
var UserFullName = context.Request.QueryString["name"].UrlDecode();
var UserEmailAddress = context.Request.QueryString["email"].UrlDecode();
//Save the user's information
var TaskToken = UserSignup.SaveUserSignup(UserFullName, UserEmailAddress);
TaskToken.Wait();
....
}
public bool IsReusable { get { return false; } }
}
Run Code Online (Sandbox Code Playgroud)
然后它调用我的中间层:
public static class UserSignup
{
public static async Task SaveUserSignup(string fullName, string emailAddress)
{
//Initialize the Parse client with the Application ID and the Windows key
ParseClient.Initialize(AppID, Key);
//Create the object
var UserObject = new ParseObject("UserSignup")
{
{"UserFullName", fullName},
{"UserEmailAddress", emailAddress}
};
//Commit the object
await UserObject.SaveAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
虽然这似乎陷入困境Wait().我的印象Wait()只是等待任务完成,然后返回正常操作.这不正确吗?
Ste*_*ary 14
您遇到了我在博客和最近的MSDN文章中描述的常见死锁问题.
简而言之,await默认情况下将async在捕获的"上下文"内恢复其方法,并且在ASP.NET上,一次只允许一个线程进入该"上下文".因此,当您调用时Wait,您正在阻止该上下文中的线程,并且在await准备好恢复该async方法时无法进入该上下文.因此上下文中的线程被阻塞Wait(等待async方法完成),并且该async方法被阻塞,等待上下文自由...死锁.
要解决这个问题,你应该"始终保持异步".在这种情况下,请使用HttpTaskAsyncHandler而不是IHttpHandler:
public class VisitorSignupHandler : HttpTaskAsyncHandler
{
public override async Task ProcessRequestAsync(HttpContext context)
{
//Get the user's name and email address
var UserFullName = context.Request.QueryString["name"].UrlDecode();
var UserEmailAddress = context.Request.QueryString["email"].UrlDecode();
//Save the user's information
var TaskToken = UserSignup.SaveUserSignup(UserFullName, UserEmailAddress);
await TaskToken;
....
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2343 次 |
| 最近记录: |