asp.net AJAX客户端调用服务器上的慢速异步进程的最佳实践

时间:2011-11-22 18:00:58

标签: asp.net ajax asynccallback

我有一个执行慢任务的服务,当它完成时我想使用AJAX更新客户端的任务结果。在我的客户端,我多次调用该任务来更新结果网格。出于理解的目的,它是一个连接测试器,它遍历连接列表以查看它们是否存活。

我已将服务实现为WCF。我将服务引用添加到Web客户端时生成异步方法。

代码工作正常,但是当回调触发时屏幕会暂时锁定 - 我认为这是因为它们都是一个接一个地发生,所有这些都快速连续地重新绘制GridView。 我不希望这个故障发生 - 我希望AJAX实现能够部分更新GridView,因为结果是通过回调从服务返回的。

我可以使这看起来很好的唯一方法是在单独的客户端线程中启动异步调用,然后使用计时器将数据重新绘制到网格(通过回调在单独的线程中更新的相同数据)

我正在做这个迷你项目作为学习练习,然后我的目标是用MVC3做同样的事情来了解差异。

代码片段(没有单独的线程,导致屏幕渲染在回调期间变慢):

//get list of connections from session
ConnectionList myConns = Session[SESSION_ID] as ConnectionList;
//pass into async service call
GetAllStatusAsync(myConns);


protected void GetAllStatusAsync(ConnectionList myConns)
{

Service1Client myClient = new WcfConnectionServiceRef.Service1Client();
myClient.AsyncWorkCompleted += new EventHandler<AsyncWorkCompletedEventArgs>(myClient_AsyncWorkCompleted);

foreach (ConnectionDetail conn in myConns.ConnectionDetail)
  {
  //this call isnt blocking, conn wont be updated until later in the callback
  myClient.AsyncWorkAsync(conn);
  }
}

//callback method from async task
void myClient_AsyncWorkCompleted(object sender, AsyncWorkCompletedEventArgs e)
{

ConnectionDetail connResult = e.Result;

//get list of connections from session
ConnectionList myConns = Session[SESSION_ID] as ConnectionList;

//update our local store
UpdateConnectionStore(connResult, myConns);

//rebind grid
BindConnectionDetailsToGrid(myConns);

}

问题是 - 这可以在asp.net / AJAX中以更好的方式完成吗? (为了避免渲染锁定问题并在结果进入时让网格部分更新)我真的不想使用单独的客户端线程,如下面的代码片段:

 // Perform processing of files async in another thread so rendering is not slowed down 
 // this is a fire and forget approach so i will never get results back unless i poll for them in timer from the main thread
ThreadPool.QueueUserWorkItem(delegate
  {
  //get list of connections from session
  ConnectionList myConns = Session[SESSION_ID] as ConnectionList;
  //pass into async service call
  GetAllStatusAsync(myConns);
  });

更新:

按要求添加页面标记:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ASForm.aspx.cs" Inherits="Web_Asp_FBMonitor.ASForm" Async="true" EnableSessionState="True" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>
        ASP.NET Connection Test (Client in ASYNC, Server in ASYNC)
    </h2>

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>


    <p>

        <%--This update panel shows the time, updated every second--%>    
        &nbsp;<asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <ContentTemplate>

            <h3> <asp:Label ID="LabelTime" runat="server" Text=""></asp:Label>  </h3>
            <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">  </asp:Timer>

            </ContentTemplate>
    </asp:UpdatePanel>
    </p>

    <p>

        <%--This update panel shows our results grid--%>
        &nbsp;<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>

            <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>

            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default.aspx">Client Sync Page</asp:HyperLink>

            <br />

            <asp:Button ID="ButtonUpdate" runat="server" Text="Update" 
                onclick="ButtonUpdate_Click" />
        </ContentTemplate>
        </asp:UpdatePanel>




    </p>



</asp:Content>

更新2:

我正在寻找一个简洁的客户端JS示例。收到的选项很好,并且非常受欢迎,但是客户端JS是我通过自己的经验而无法获得的,并将为此奖励。

4 个答案:

答案 0 :(得分:2)

由于ASP UpdatePanel,您会看到所谓的“屏幕锁定”。

ASP.NET WebForms试图使Web像Windows窗体一样。令人敬佩?取决于你问谁。

当您使用UpdatePanel时,ASP.NET将服务器端控件存储在ViewState中,对该ViewState进行必要的更改(在您的情况下,它会根据代码更新页面)在Timer_TickButtonUpdate_Click函数中。然后,它使用这个新数据刷新页面,导致您描述的屏幕锁定。

要解决这个问题,你必须使用真正的AJAX。很多人使用jQuery AJAX函数和以下选项之一来做到这一点:

  • ASP.NET WebMethods
  • WCF服务
  • 单独的ASP.NET页面

这里有很多关于通过jQuery挂起ASP.NET WebMethods的问题,还有一些关于加载ASP.NET页面的问题,但没有关于AJAX和WCF的问题。

如果您选择使用AJAX和jQuery,您的结果页面将如下所示:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ASForm.aspx.cs" Inherits="Web_Asp_FBMonitor.ASForm" Async="true" EnableSessionState="True" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<!-- include jQuery library here -->
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        UpdateGrid();

        // Separate AJAX call to another page, WCF service, or ASP.NET WebMethod for the Timer results
    });

    function UpdateGrid() {
        $.ajax({ url: "GridViewResults.aspx",
            done: function (result) {
                $("#gridResults").html(result.d);
            }
        });
    }
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>
        ASP.NET Connection Test (Client in ASYNC, Server in ASYNC)
    </h2>

    <p>
        <h3> <span id="timer"></span> </h3>
    </p>

    <p id="gridResults">
    </p>
    <button id="ButtonUpdate" onclick="UpdateGrid();">Update</button>
</asp:Content>

然后,在一个单独的页面上(我在上面任意称它为GridViewResults.aspx),你有:

<asp:GridView ID="GridView1" runat="server"></asp:GridView>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default.aspx">Client Sync Page</asp:HyperLink>
<br />

答案 1 :(得分:1)

您可能想要查看ASP.net中的“异步”页面。这些将允许您进行单个AJAX回调并让服务器在服务器端异步执行所有轮询。然后,当所有任务都异步返回并且您有一整套数据时,您可以重新绑定网格。

链接到解释thsi的文章:

http://msdn.microsoft.com/en-us/magazine/cc163725.aspx


好的,根据评论的反馈,您希望在每次更新返回时更新网格。我不确定你是如何从浏览器中踢出你的AJAX请求的,但是你可能想要从客户端异步地查看这些请求(类似jQuery这里有用),然后再次使用脚本重绘特定的行得到结果时所需的网格。

答案 2 :(得分:1)

从您发布的代码中,看起来您从客户端向服务器进行一次调用,然后服务器进行一系列异步调用。当异步结果到达时,它会更新网格,当最后一个结果到达时,它会将更新后的网格返回给客户端。

您可以通过在第一个异步响应到达后强制服务器返回来解决此问题。但是,仅仅删除未完成的请求就存在潜在的清理问题。如果您想要使用该选项,如果您可以发布管理传入请求的服务器端代码部分,将会有所帮助。

如果您希望在结果到达服务器时获得网格更新,则可能会有一些更清晰的选择:

  1. 不是从客户端发出一个调用服务器上的多个异步调用的调用,而是从客户端发出多个异步JS调用,每个服务器上都有一个同步调用。每次同步调用完成后,它将返回到客户端。然后,客户端JS代码将找到并更新网格的相应部分。

  2. 切换到使用WebSockets。这是一个双向数据连接。服务器可以使用异步请求定期轮询信息,然后在到达时将结果发送给客户端。然后,客户端将使用脚本(如上面的#1)来更新网格。

  3. 使用长轮询。有一个后台线程定期轮询信息,并维护具有当前状态和序列号或时间戳的数据结构。当客户端发出更新的Ajax请求时,它会传递它收到的最后一个时间戳或序列号。然后,服务器代码查看后台线程的数据结构中是否有任何新内容。如果是这样,它会更新网格并返回。如果没有,它将进入休眠状态(等待共享锁),直到后台线程收到更新,此时它会发出锁定信号,导致请求线程被唤醒,使用最新数据更新页面并返回。 / p>

  4. 下面是一些使用jQuery进行异步Ajax调用的示例代码:

    $.get('myinfo.ashx', function(data) {
      $('.result').html(data);
    })
    

    更多详情请见:http://api.jquery.com/jQuery.get/

答案 3 :(得分:0)

您是否考虑过使用长轮询/持久连接。

现在有一个很好的框架可以让它在ASP.net中轻松实现,名为SignalR

以下是一些可以帮助您入门的文章:

http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx

http://www.amazedsaint.com/2011/11/introduction-ksigdo-knockout-signalr-to.html

对于您所描述的问题,我觉得这听起来很合适,因为当数据被推送到订阅者时,它会允许屏幕更新。

相关问题