BackgrounderWorker在try-catch块中停止

时间:2012-08-12 09:42:07

标签: c# backgroundworker

//static int var1, var2, var3;
//static List<string> list;

    public static void MyMethod(Object obj, int times)
    {
        List = doc1.Descendants("Order")
            .Select(d => d.Value)
            .ToList();
        for (int i = 0; i < List.Count; i++)
        {
            try
            {
                var item = (from m in doc1.Elements("list").Elements("Order")
                                where m.Value == List[i]
                                select m);

                item.Remove();

                doc1.Save(path1);
                var1 = doc1.Root.Descendants("Order").Count();


                //DoSomethingHeavy with List[i]

                doc2.Element("list2").Add(new XElement("Order", List[i]));
                doc2.Save(path2);


                 var2= doc2.Root.Descendants("Order").Count();

            }
            catch (Exception)
            {
                doc3.Element("list3").Add(new XElement("Order", List[i]));
                doc3.Save(path3);

                var3 = doc3.Root.Descendants("Order").Count();

            }
        }
    }

这是公共静态类中的MyMethod。 我想让它在BackgroundWorker下的表单中运行,以便能够暂停和恢复执行。

我正在使用这个课程:

public class BackgroundLoading
{
    public BackgroundWorker Bw;
    public delegate void RunFunction();
    public RunFunction thisFunction;



    public BackgroundLoading(RunFunction newFunction)
    {
        thisFunction = newFunction;
        Bw = new BackgroundWorker();
        Bw.DoWork += new DoWorkEventHandler(Bw_DoWork);
        Bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Bw_RunWorkerCompleted);
    }

    public void Start()
    {
        Bw.RunWorkerAsync();
    }

    void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            //an error occured
            MessageBox.Show("an error occured: " + e.Error.Message);
        }
        if (e.Cancelled)
        {
            //an error occured
            MessageBox.Show("Job cancelled");
        }
        else
        {
            MessageBox.Show("Job completed");
        }

    }

    void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        MessageBox.Show(" *");
    }

    void Bw_DoWork(object sender, DoWorkEventArgs e)
    {
        if (thisFunction != null)
            thisFunction();
    }
}

 //class to implement

然后,在myForm中:

private void button1_Click(object sender, EventArgs e)
    {
        BackgroundLoading bl = new BackgroundLoading(MyMethod());
        bl.Start();
    }

我是BackgroundWorker的新手,可能我没有以正确的方式使用它。 单击StopExecution按钮时,并非所有文档(doc1,doc2,doc3)都已保存。 那么如何避免在try-catch块中停止?

1 个答案:

答案 0 :(得分:1)

  1. WorkerSupportsCancellation设置为True以允许BackgroundWorker支持取消。
  2. 点击取消按钮调用CancelAsync()方法。
  3. 通过拆分为2种方法来更改方法。一个应该得到一个项目编号,另一个将逐项工作。
  4. 在您的DoWork()方法中,检查是否有cancellation pending并完成您的流程(如果有)。

      void Bw_DoWork(object sender, DoWorkEventArgs e)
      {
    
        //in your loop test every time Cancel flag       
        for (int i = 0; i < MyMethodGetItemcount(); i++)
        {
            MyMethod(i);//item by item
            if(yourbackgroundworker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
     }
    
相关问题