从FormClosing触发时,不会触发RunWorkerCompleted

时间:2013-04-10 19:10:42

标签: c# forms timer backgroundworker formclosing

我有一个表单需要通过Web服务调用将未保存的数据保存到外部数据库。当用户手动保存数据时,会触发RunWorkerCompleted,但是当我通过FormClosing事件调用该方法时,则不会触发。

计时器在用户修改表单中的值几秒后滴答,并在用户修改另一个值时重置,想法是'toSend'列表有多个值,我可以发布多个更改因为Web服务调用需要大量的开销。

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (PublishBackgroundWorker.IsBusy)
            return;

        List<object> toSend = new List<object>();

        // Figure out what changed and add it to toSend ...
        toSend.Add(changedItems);

        if (toSend.Count >= 1)
            PublishBackgroundWorker.RunWorkerAsync(toSend);
    }

    private void PublishBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        if (((List<object>)(e.Argument)).Count > 0)
        {
            Service.SrvObjects[] ret = Svc.PublishItems(e.Argument));
        }
    }

    private void PublishBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Ready" });
    }

    private void IPTUserInterfaceForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        timer1.Enabled = false;
        timer1_Tick(this, new EventArgs());
        //Application.DoEvents();
        while (PublishBackgroundWorker.IsBusy)
            System.Threading.Thread.Sleep(100);
    }

这有意义吗?当用户更改一个值,并在计时器关闭之前关闭表单时,我手动勾选希望PublishBackgroundWorker.IsBusy在某些时候是假的,并且它永远不会是因为从不调用RunWorkerCompleted。

1 个答案:

答案 0 :(得分:2)

问题是你的Backgroundworker并不忙,只是因为你调用了timerTick方法。因此,在方法的其余部分运行并且表单关闭并且应用程序关闭之前,永远不会达到此代码:

    while (PublishBackgroundWorker.IsBusy)
        System.Threading.Thread.Sleep(100);