Frage

I have a form that needs to save unsaved data to an external DB via a web service call. When the user manually saves the data, the RunWorkerCompleted gets triggered, however not when I call the method via the FormClosing event.

The timer ticks after a few seconds after the user modifies a value in the form, and gets reset if the user modifies another value, the idea being that the 'toSend' list has more than one value and I can publish multiple changes at a time since web service calls are a lot of overhead.

    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);
    }

Does this make sense? When the user changes a value, and closes the form before the timer goes off, I manually Tick hoping that the PublishBackgroundWorker.IsBusy is false at some point, and it never is because RunWorkerCompleted is never called.

War es hilfreich?

Lösung

The problem is that your Backgroundworker is not busy just because you call the timerTick method. Therefore this code is never reached before the rest of the method runs through and the form gets closed and the application closes:

    while (PublishBackgroundWorker.IsBusy)
        System.Threading.Thread.Sleep(100);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top