2014-02-10 21 views
-1

如何取消C#中的线程,当我调用Web服务,例如:我怎样才能取消bacgroundworker在C#中处理调用Web服务时

这下面的代码:

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

我想用方法,函数或事件点击来取消线程,你能否帮我一下。

我不开发Web服务,我只使用这些方法。我在C#中使用3.5框架。

回答

0

有取消BackgroundWorker的方法:

doWorkAnuncios.CancelAsync(); 

,然后你可以做的东西,如果它是在完成功能取消与否:

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 
     } 
    } 
+0

他*已经*借力取消支持BGW。他的代码是正确的。 – Servy

+0

是的,但现在他想取消,它只是我显示的第一行,bw.CancelAsync() –

相关问题