【发布时间】:2018-05-01 19:30:13
【问题描述】:
问题总结:
我正在尝试使用 PageMethods 从 HTML 页面调用 C# 函数。问题是我正在调用的 C# 函数被标记为异步并且将等待其他函数的完成。当 PageMethods 调用嵌套的异步 C# 函数时,C# 代码似乎死锁了。
我已经给出了一个示例 ASP.NET 页面,其后面带有 C# 编码来说明我正在尝试使用的习语。
WebForm1.aspx 示例
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title></title></head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<div>
<input type="button" value="Show Function timing" onclick="GetTiming()"/>
</div>
</form>
</body>
<script type="text/javascript">
function GetTiming() {
console.log("GetTiming function started.");
PageMethods.GetFunctionTiming(
function (response, userContext, methodName) { window.alert(response.Result); }
);
console.log("GetTiming function ended."); // This line gets hit!
}
</script>
</html>
WebForm1.aspx.cs 示例
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Web.Services;
using System.Web.UI;
namespace WebApplication3
{
public partial class WebForm1 : Page
{
protected void Page_Load(object sender, EventArgs e) { }
[WebMethod]
public static async Task<string> GetFunctionTiming()
{
string returnString = "Start time: " + DateTime.Now.ToString();
Debug.WriteLine("Calling to business logic.");
await Task.Delay(1000); // This seems to deadlock
// Task.Delay(1000).Wait(); // This idiom would work if uncommented.
Debug.WriteLine("Business logic completed."); // This line doesn't get hit if we await the Task!
return returnString + "\nEnd time: "+ DateTime.Now.ToString();
}
}
}
问题:
我绝对需要能够从我的网页 UI 调用异步代码。我想使用 async/await 功能来做到这一点,但我无法弄清楚如何去做。我目前正在通过使用 Task.Wait() 和 Task.Result 而不是 async/await 来解决这个缺陷,但这显然不是推荐的长期解决方案。
如何等待服务器端异步函数在 PageMethods 调用的上下文中???
我真的非常想了解这里发生了什么,以及为什么从控制台调用异步方法时它不会发生应用程序。
【问题讨论】:
-
出于好奇,为什么是页面方法而不是 jquery 和 ajax?
-
为什么绝对需要使用异步代码?是什么迫使你这样做?
-
awaitdeadlocking 和.Wait()not deadlocking 没有任何意义。Task.Delay并没有真正发生这种情况。是吗? -
我最初使用 PageMethods 是因为它与 IIS 和 .net 堆栈紧密集成,因此在我工作的 C# 商店中使用它似乎是自然的选择。我开始为这个决定感到后悔,在这一点上,我坚持着固执和好奇。 ;-)
-
我的真实代码使用异步HTTP请求。我只使用 Task.Delay 来说明异步/等待编程习惯的奇怪行为。
标签: c# asp.net asynchronous async-await pagemethods