【问题标题】:BackgroundWorker and Timer issues - UI FreezeBackgroundWorker 和 Timer 问题 - UI 冻结
【发布时间】:2014-07-18 05:17:30
【问题描述】:

最初我的代码有一个Timer,它会不断地ping 服务器以查看它是否已连接。但是,我也有一个Timer 以显示当前时间。这是它最初的样子:

public Main()
{
    /* let's check if there is a connection to the database */
    isDbAvail = new Timer();
    isDbAvail.Interval = 8000;
    isDbAvail.Tick += new EventHandler(isOnline);
    isDbAvail.Start();

    /* the clock */
    clock = new Timer();
    clock.Interval = 1000;
    clock.Tick += new EventHandler(clockTimer_Tick);
    clock.Start();
}

private void isOnline(object sender, EventArgs e)
{
    Connection connection = new Connection();
    changeStatus(connection.isDbAvail());
}

private void clockTimer_Tick(object sender, EventArgs e)
{
    clock.Text = DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss");
}

到目前为止,一切正常,除了在检查数据库时,整个 UI 会冻结并延迟大约 3 秒。我做了一些研究,找到了 BackgroundWorker 并将所有内容更改为以下内容:

public Main()
{
    isDbAvail = new BackgroundWorker();
    isDbAvail.DoWork += isOnline;

        /* the clock */
    clock = new Timer();
    clock.Interval = 1000;
    clock.Tick += new EventHandler(clockTimer_Tick);
    clock.Start();
}

private void isOnline(object sender, DoWorkEventArgs e)
{
    while (true)
    {
        Thread.Sleep(8000);
        Connection connection = new Connection();
        changeStatus(connection.isDbAvail());
    }
}

当我运行它时,什么都没有发生,我也没有收到任何错误。我很确定这里缺少一些我似乎无法掌握的非常重要的东西。

【问题讨论】:

    标签: c# timer backgroundworker


    【解决方案1】:

    添加

    isDbAvail.RunWorkerAsync();
    

    之后

    isDbAvail.DoWork 
    

    【讨论】:

    • 哈哈,这很简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    相关资源
    最近更新 更多