【问题标题】:How can I cancel the bacgroundworker when processing call web service in C#在 C# 中处理调用 Web 服务时如何取消 bacgroundworker
【发布时间】:2014-03-08 06:36:51
【问题描述】:

如何在 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 框架。

【问题讨论】:

    标签: c# .net-3.5


    【解决方案1】:

    有一种方法可以取消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
            }
        }
    

    【讨论】:

    • 已经利用了 BGW 的取消支持。就在他的代码里。
    • 是的,但现在他想取消,这只是我显示的第一行,bw.CancelAsync()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2013-11-09
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多