简体   繁体   English

从ASP.NET页面调用异步方法使我等待结果

[英]Calling async method from ASP.NET page makes me wait for the result

From my ASP.NET Page I call a method from a referenced project like this: 在我的ASP.NET页面中,我从引用的项目中调用一个方法,如下所示:

Dim oValServiceAgent As New ServiceAgents.ValServiceAgent(System.Security.Principal.TokenImpersonationLevel.Impersonation, "ValEndPointName")
Using (CType(HttpContext.Current.User.Identity, System.Security.Principal.WindowsIdentity).Impersonate())
    oValServiceAgent.DoStuffAsync()
End Using

Referenced project ServiceAgents with class valServiceAgent: 用类valServiceAgent引用的项目ServiceAgents:

public void DoStuffAsync()
{
    //invokes async method using delegates
}

I want the user to be able to navigate to a different page before the DoStuffAsync() is finished. 我希望用户能够在DoStuffAsync()完成之前导航到其他页面。 In the current situation this is not possible. 在当前情况下这是不可能的。

I'm using VS2010 and target .NET framework 3.5 我正在使用VS2010和目标.NET Framework 3.5

Have you tried calling Request.End() after you start the async process? 启动异步过程后,您是否尝试过调用Request.End()? That will force the current request to end right away. 这将迫使当前请求立即结束。 Not sure if that would work but something for you to try. 不知道这是否行得通,但您可以尝试一下。

Note that launching background threads is not a preferable thing to do in web pages since you are not guaranteed that that thread will not be killed before completing what it is trying to complete because of app pool recycling. 请注意,启动后台线程不是在Web页面中最好的操作,因为由于应用程序池的回收,不能保证在完成尝试完成的线程之前不会杀死该线程。 That thread becomes part of the current application pool and will be at the mercy of it after you kick it off. 该线程将成为当前应用程序池的一部分,并且在您启动该线程后将受其支配。 The approach I prefer is to queue the operation and process it outside of the web application instead. 我更喜欢的方法是将操作排队并在Web应用程序之外进行处理。 You can use whatever queue framework you would like or even roll your own by writing a record into a table or something. 您可以使用任何想要的队列框架,甚至可以通过将记录写入表或其他东西来滚动自己的队列框架。

The problem was in the async method as Falanwe suggested, not in my asp.net code. 问题出在Falanwe建议的异步方法中,而不是我的asp.net代码中。

Thanks for the suggestions. 感谢您的建议。

Here some points 这里有几点

  • async and await keyword methods are .Net 4.5 features. asyncawait关键字方法是.Net 4.5的功能。
  • async suffix is a convention only for methods that support async 异步后缀仅用于支持异步的方法的约定

More on async here in .Net 4.5 更多关于异步这里在.NET 4.5

In .net 3.5 you should use Thread or a BackgroundWorker to create your own asynchronous method. 在.net 3.5中,您应该使用ThreadBackgroundWorker创建自己的异步方法。

We need more precision on your async method body to give you further help 我们需要您的异步方法主体更精确,以便为您提供进一步的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM