【问题标题】:ASP.Net WebForms running mulitple queries at the same time同时运行多个查询的 ASP.Net WebForms
【发布时间】:2010-08-24 20:58:08
【问题描述】:

这适用于企业网络应用程序。

我们正在构建一个首页/仪表板,用于查询我们的数据库以获取实时统计信息。该页面有 3 个更新面板,每个更新面板都有一个用户控件,用于为其框提取数据。让我们调用用户控件 UC_NotStarted、UC_Active 和 UC_Finished。

我们已经构建了返回数据的查询,所有这些查询都需要一段时间才能运行(每个约 7 秒)。因此,如果我们让第一页使用一个更新面板运行,图像会旋转约 21 秒并显示所有内容。我们将该代码分解为 3 个更新面板,并将加载设置为有条件的。当我们这样做时,我们每 7 秒加载一个盒子。这是朝着正确方向迈出的一步,但它们是按顺序加载的(UC_NotStarted 被查询等待 7 秒并显示,然后 UC_Active 持续 7 秒,最后 UC_Finished 运行 7 秒)。我们仍然是 21 秒,但数据每 7 秒显示一次。

我们希望在 7 秒内显示所有数据,因为所有更新面板都应该同时获取数据。我现在不是使用 LinqToSQL 来提取数据,而是倾向于使用 Web 服务来获取它,但不确定这是否可行。

【问题讨论】:

    标签: asp.net ajax web-services updatepanel


    【解决方案1】:

    查看ThreadPool,特别是QueueUserWorkItem 方法。这样做很可能同时运行 3 个查询并处于 Thread.Sleep 循环中等待所有三个查询完成执行,以便您可以更新页面的所有相关部分。

    以下代码几乎肯定需要调整,但可以让您大致了解如何执行此操作:

    public class QueryResult
    {
        public bool Completed;
        public DataTable Result;
        public int ResultId;
    }
    
    public void GetData()
    {
        var QueryResults = new List<QueryResult>();
        queryResults.Add(new QueryResult() { ResultId = 1 });
        queryResults.Add(new QueryResult() { ResultId = 2 });
        queryResults.Add(new QueryResult() { ResultId = 3 });
    
        ThreadPool.QueueUserWorkItem(new WaitCallback(QueryRoutine), queryResults[0]);
        ThreadPool.QueueUserWorkItem(new WaitCallback(QueryRoutine), queryResults[1]);
        ThreadPool.QueueUserWorkItem(new WaitCallback(QueryRoutine), queryResults[2]);
    
        var completedResults = new List<QueryResult>();
        while(QueryResults.Count > 0)
        {
            for(int 1 = QueryResults.Count - 1; i >= 0; i--;)
            {
                if (queryResults[i].Completed)
                {
                    completedResults.Add(queryResults[i]);
                    queryResults.RemoveAt(i);
                }
            }
            Thread.Sleep(500);
        }
    
        // All background threads have completed, do something with the results,
        // return them to the front-end, etc,..
    }
    
    public void QueryRoutine(object qR)
    {
        var queryResult = (QueryResult)qR;
    
        // perform long running query here on a distinct thread, as QueryRoutine 
        // is now being run on three separate threads by the calls to QueueUserWorkItem
        // based on queryResult.ResultId picking the relevant query for values 
        // of 1, 2 or 3
    
        queryResult.Completed = true;
    }
    

    【讨论】:

    • 感谢您的回答。看起来很有趣。本周我将尝试在我们的网站上实现这一点,然后我会报告结果。
    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多