C#后台工作程序 - 使用List <employee>报告进度

时间:2016-10-31 14:39:09

标签: c# backgroundworker

查看我的代码

public partial class Form1 : Form
{
    BackgroundWorker m_oWorker;

    public Form1()
    {
        InitializeComponent();

        m_oWorker = new BackgroundWorker();

        // Create a background worker thread that ReportsProgress &
        // SupportsCancellation
        // Hook up the appropriate events.
        m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
        m_oWorker.ProgressChanged += new ProgressChangedEventHandler
                (m_oWorker_ProgressChanged);
        m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler
                (m_oWorker_RunWorkerCompleted);
        m_oWorker.WorkerReportsProgress = true;
        m_oWorker.WorkerSupportsCancellation = true;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        m_oWorker.RunWorkerAsync();
    }

    List<Employee> oEmp = new List<Employee>();

    void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // The sender is the BackgroundWorker object we need it to
        // report progress and check for cancellation.
        //NOTE : Never play with the UI thread here...
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(100);

            // Periodically report progress to the main thread so that it can
            // update the UI.  In most cases you'll just need to send an
            // integer that will update a ProgressBar     

            oEmp.Add(new Employee(1, "Dipak"));
            m_oWorker.ReportProgress(i, new object[] { oEmp });
            // Periodically check if a cancellation request is pending.
            // If the user clicks cancel the line
            // m_AsyncWorker.CancelAsync(); if ran above.  This
            // sets the CancellationPending to true.
            // You must check this flag in here and react to it.
            // We react to it by setting e.Cancel to true and leaving
            if (m_oWorker.CancellationPending)
            {
                // Set the e.Cancel flag so that the WorkerCompleted event
                // knows that the process was cancelled.
                e.Cancel = true;
                m_oWorker.ReportProgress(0);
                return;
            }
        }

        //Report 100% completion on operation completed
        m_oWorker.ReportProgress(100);
    }

     void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        List<Employee> oEmp = (List<Employee>)e.UserState;
        lblStatus.Text = "Processing......" + e.ProgressPercentage.ToString() + "%";
    }

     void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
     {
         // The background process is complete. We need to inspect
         // our response to see if an error occurred, a cancel was
         // requested or if we completed successfully.  
         if (e.Cancelled)
         {
             lblStatus.Text = "Task Cancelled.";
         }

         // Check to see if an error occurred in the background process.

         else if (e.Error != null)
         {
             lblStatus.Text = "Error while performing background operation.";
         }
         else
         {
             // Everything completed normally.
             lblStatus.Text = "Task Completed...";
         }
     }
}

public class Employee
{
    int ID = 0;
    string Name = "";

    public Employee()
    {

    }

    public Employee(int ID, string Name)
    {
        this.ID = ID;
        this.Name = Name;
    }
}

我将自定义数据传递给ProgressChanged event,如m_oWorker.ReportProgress(i, new object[] { oEmp });

请告诉我如何从ProgressChanged event回读它。

我试过这个却失败了。

 void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    List<Employee> oEmp = (List<Employee>)e.UserState;
    lblStatus.Text = "Processing......" + e.ProgressPercentage.ToString() + "%";
}

1 个答案:

答案 0 :(得分:0)

如果要将列表作为UserState,则传递列表并删除对象数组。

m_oWorker.ReportProgress(i, oEmp);

您仍然需要同步对列表的访问权限,不进行任何复制,您仍然有两个线程尝试访问它。