C#,后台工人类

时间:2011-02-09 11:13:36

标签: c# winforms backgroundworker

当我编译这段代码时,我得到他的错误,对象引用设置为null,错误位置在Dowork,argumenttest.valueone = 8;

public partial class Form1 : Form
{
    BackgroundWorker bgw1 = new BackgroundWorker();
    public Form1()
    {
        InitializeComponent();
        // bgw1.RunWorkerAsync(test1);

        test test1 = new test
        {
            valueone = 5,
            valuetwo = 10
        };
        bgw1.RunWorkerAsync(test1);
    }

    class test
    {

        public int valueone { get; set; }
        public int valuetwo { get; set; }
    }

    private void bgw1_DoWork(Object sender, DoWorkEventArgs e)
    {
        test argumenttest = e.Argument as test;
        Thread.Sleep(10);

        argumenttest.valueone = 8;
        argumenttest.valuetwo = 10;

        e.Result = argumenttest;
    }

    private void bgw1_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
    {
        test test12 = e.Result as test;
        button1.Text = test12.valueone.ToString();// +test.valuetwo.ToString();
        //this.Text = test.valueone.ToString() + " "+ test.valuetwo.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        bgw1.DoWork += bgw1_DoWork;
        bgw1.RunWorkerCompleted += bgw1_RunWorkerCompleted;
        //bgw1.RunWorkerAsync(test);

    }
}

3 个答案:

答案 0 :(得分:4)

argumenttest有两种可能的方式null

  1. argumenttest已作为null发送到RunWorkerAsync

  2. e.Argument as test; e.Argument不符合testas运算符使其null

  3. 很难看出哪一个,因为上面的代码示例非常混乱。

    修改

    您能否确认您的代码是完全,因为decyclone已编辑过它?在这种情况下,它看起来很好,应该尽我所能。

    在DoWork方法的第一行设置断点,在调试时,您应该可以通过将鼠标悬停在e.Argument上轻松查看1.或2.是否存在问题。

答案 1 :(得分:1)

我看到的一个问题是你在运行worker之前没有设置事件处理程序,所以这2行

    bgw1.DoWork += bgw1_DoWork;
    bgw1.RunWorkerCompleted += bgw1_RunWorkerCompleted;

必须在

之前调用
    bgw1.RunWorkerAsync(test1);

答案 2 :(得分:1)

您应该在表单加载中或在调用RunWorkerAsync之前订阅DoWork和RunCompleted。

bgw1.DoWork += bgw1_DoWork;
bgw1.RunWorkerCompleted += bgw1_RunWorkerCompleted;

将上述行从Button Click事件处理程序移动到Form_Load。

bgw1.RunWorkerAsync(test1);移动到Form Load方法的按钮单击处理程序。