El enhebrado comienza de nuevo después de una pausa

I am using threading in my code , thread are created using function:

private void InitializeBackgoundWorkers()
{

    for (int f = 0; f < maxThreads; f++)
    {
        listBox1.Items.Insert(0, "Starting Thread : " + (f + 1));
        threadArray[f] = new BackgroundWorker();
        threadArray[f].DoWork +=
            new DoWorkEventHandler(backgroundWorkerFiles_DoWork);
        threadArray[f].RunWorkerCompleted +=
            new RunWorkerCompletedEventHandler(backgroundWorkerFiles_RunWorkerCompleted);
        threadArray[f].ProgressChanged +=
            new ProgressChangedEventHandler(backgroundWorkerFiles_ProgressChanged);
        threadArray[f].WorkerReportsProgress = true;
        threadArray[f].WorkerSupportsCancellation = true;

    }
}

And the doevent is something like :

private void backgroundWorkerFiles_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = sender as BackgroundWorker;

    int flag = 0;

    while (rowCounter < allPostingRows.Tables[0].Rows.Count && flag == 0)
    {

        for (int i = 0; i < maxThreads; i++)
        {

            if (threadArray[i].CancellationPending == true)
            {
                flag = 1;
                threadArray[i].CancelAsync();
                worker.ReportProgress(0, "Thread Paused:");
            }

        }

        if (flag == 0)
        {
             //perform work here
            }
    }
}

And on button i try to cancel the threads using:

for (int i = 0; i < maxThreads; i++)
{
    threadArray[i].CancelAsync();
}

Am i cancelling the thread correctly? As when they get canceled i see the line in listbox saying thread cancelled so it does go to the cancellation code but after some time it restarts

Gracias

preguntado el 31 de julio de 12 a las 14:07

How are the workers started? Do all workers restart? Do they restart from the beginning? -

@PeterRitchie i reduced all the extra code and made it nice and simple any help now? -

1 Respuestas

I don't think you really understand BackgroundWorker. La DoWork event handler is supposed to be a handler for one unit of work. DoWork is called with one thread. It doesn't make sense to call CancelAsync desde dentro de un DoWork handler--that's independent of any and all other BackgroundWorker's. Within the DoWork handler it should only be checking one CancellationPending, the sender's (once cast to BackgroundWorker, en tu caso worker).

But, otherwise, calling CancelAsync from the UI is the correct way to cancel a particular BackgroundWorker.

Background workers are not "thread"s. You''re not cancelling a thread, you're cancelling the worker--which allows the DoWork handler a chance to exit before it is done it's work.

Respondido 31 Jul 12, 20:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.