对于定时器中的循环 - C#

时间:2012-08-21 04:24:02

标签: c# winforms browser for-loop timer

我有一个Datagridview,每行包含很少的列和数据。我需要定期发送完整的Datagridview数据,每个行数据一次一个,顺序发送到我的应用程序中的web browser,这实际上会将此行数据附加到网站的URL,该URL将回显附加到的任何数据它。因此,为此目的,我使用了timer,它会为每10 seconds发送一次所有数据。在计时器内部每次发送一行我使用了以下for loop

private void tmr_senddata_Tick(object sender, EventArgs e)
{
    if(dg_parameters.Rows.Count!=1)
    {
        for (int i = 0; i < dg_parameters.Rows.Count-1; i++)
        {
            string row = "";
            string cell = "";
            for (int j = 0; j < dg_parameters.Columns.Count; j++)
            {
                cell = cell + dg_parameters.Rows[i].Cells[j].Value;
                cell = cell + "@";
                row = cell;
            }
            string uri = webBrowser1.Url + row;
            webBrowser1.Navigate(uri);
        }
    }
}

现在我最终只有last row being displayed on the browser。这是因为当我的浏览器导航到我的循环中第一次指定的URL时,下一次迭代需要和URL更改。因此,只有我的最后一行数据才能正确导航并显示在浏览器上。如何每次停止指定时间的for循环,以便我可以看到我的浏览器导航到URL。我相信Thread.Sleep()不是一个好主意,因为它会阻止我的UI线程。

更新:这是一个用于测试特定方案的模拟应用程序。所以请忽略这样做的原因。问题的解决方案将会有所帮助。

2 个答案:

答案 0 :(得分:4)

在您的应用程序启动时将dg_parameters.Rows放入Queue

每次计时器触发时,请致电myQueue.Dequeue以获取下一个要使用的项目。

答案 1 :(得分:0)

为什么不使用WebBrowser.DocumentCompleted Event
文档完全下载后,您可以调用tmr_senddata_Tick 如果你不希望你的界面受到影响,你也可以在后台线程上传输整个东西。

实施例: -

private void setevent()
{
    webBrowserForPrinting.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(NavigateTo);

}

private void NavigateTo(object sender,
    WebBrowserDocumentCompletedEventArgs e)
{
   //Pause thread as per the need.
   if(dg_parameters.Rows.Count!=1)
        {
            for (int i = 0; i < dg_parameters.Rows.Count-1; i++)
            {
                string row = "";
                string cell = "";
                for (int j = 0; j < dg_parameters.Columns.Count; j++)
                {
                    cell = cell + dg_parameters.Rows[i].Cells[j].Value;
                    cell = cell + "@";
                    row = cell;
                }
                string uri = webBrowser1.Url + row;
                webBrowser1.Navigate(uri);
            }
        }
}