How can I cancel the bacgroundworker when processing call web service in C#

StackOverflow https://stackoverflow.com/questions/21685530

  •  09-10-2022
  •  | 
  •  

Question

How can I cancel in C# the threading, when I call a web service, for example:

This code below:

private BackgroundWorker doWorkAnuncios;
public myclass()
{
  doWorkAnuncios = new BackgroundWorker();
  doWorkAnuncios.WorkerSupportsCancellation = true;
}

public void someMethod()

{
  doWorkAnuncios.RunWorkerCompleted += new RunWorkerCompletedEventHandler(doWorkAnuncios_RunWorkerCompleted);
                        doWorkAnuncios.DoWork += new DoWorkEventHandler(doWorkAnuncios_DoWork);
                        doWorkAnuncios.RunWorkerAsync();
}



private void doWorkAnuncios_DoWork(object sender, DoWorkEventArgs e)//Call the web service
    {
        _dataCustomer = new Customers(); //this object sends the customer number
        _lstCustomers = _dataCustomer.GetDetailsCustomers(CustomerNumber);//Send a customer number

        //In this part check the CancellationPending, but when it finish the process in the web service, 
        //if i decide to cancel the process, it do not cancell the request.**

        if (doWorkAnuncios.CancellationPending)//try to cancel the background
        {
            e.Cancel = true;
            return;
        }
    }

I want to cancel the threading with a method, function or event click, can you please help me.

I do not develop the web service, I only consume the methods. I use the 3.5 framework in C#.

Était-ce utile?

La solution

there is a method to cancel a BackgroundWorker:

doWorkAnuncios.CancelAsync();

and then you can do something if it was cancelled or not at the completed function:

    private void doWorkAnuncios_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if ((e.Cancelled == true))
        {
          //do something if it was cancelled
        }

        else if (!(e.Error == null))
        {
            //when an error occur
        }

        else
        {
            //ended the background with no problems or cancel, just like you have
        }
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top