无法从编写为BackgroundWorker的列表中读取元素

时间:2013-01-12 18:54:37

标签: c# list

我在阅读字符串列表时遇到问题,这是我的代码。

public partial class form : Form
{
    public static List<String> errores = new List<String>();

   private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){

        BackgroundWorker bw = sender as BackgroundWorker;

        // Extract the argument. 
        string arg = (string)e.Argument;

        // Start the time-consuming operation.
        //  e.Result =
        if (tags.prog2(arg) == false)
        {
            //guardar en lista de no completadas
            form.errores.Add("a");

        }
  //some code here
        }




    private void buscar()
    {

    //Some code here
        foreach (string i in rutas)
            {
                backgroundWorker1 = new System.ComponentModel.BackgroundWorker();

                backgroundWorker1.WorkerSupportsCancellation = true;
                backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
                backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
                backgroundWorker1.RunWorkerAsync(i);                    


            }
          foreach (string prime in form.errores)
            {
                MessageBox.Show(prime);
            }
    }
}

但是列表中没有元素,为什么会发生这种情况?

显然我称之为两个职能

Aclaration function1是一个backgroundWorker,所以它被调用了太多次,我不知道这是否与错误有关。

1 个答案:

答案 0 :(得分:1)

  

Aclaration function1它是一个backgroundWorker,所以它调用了太多次,我不知道这是否与错误有关

在调用read()之前调用似乎function1()。由于BackgroundWorker调用了function1,所以很有可能。

你应该留一个标志来表明是否要调用function1。如果没有打电话,你应该采取预防措施。

作为参考,以下代码运行良好(并生成"aaa"输出)

form f = new form(); 
f.Test();

public partial class form 
{
    public static List<String> errores = new List<String>();

    private void function1()
    {
        form.errores.Add("aaa");
    }

    //Now I try to read it in other function.

    private void read()
    {
        foreach (string i in form.errores)
        {
            Console.WriteLine(i);
        }
    }

    public void Test()
    {
       function1();
       read();
    }
}