当我调用Web服务时,如何在C#中取消线程,例如:
以下代码:
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 :(得分: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
}
}