加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么一个事件是空的? (你调用的对象是空的)

发布时间:2020-12-16 00:08:40 所属栏目:百科 来源:网络整理
导读:我有一个带有按钮,标签和进度条的表单,因此当我单击该按钮时,它会创建一个b类实例来运行一个进程.一旦完成该过程,它将调用EventHandler在主窗体的标签中显示“done”! 我创建了一个委托事件(SetStatusEvent)来执行此操作.当我在EventHandler(usbforProcessE
我有一个带有按钮,标签和进度条的表单,因此当我单击该按钮时,它会创建一个b类实例来运行一个进程.一旦完成该过程,它将调用EventHandler在主窗体的标签中显示“done”!

我创建了一个委托事件(SetStatusEvent)来执行此操作.当我在EventHandler(usbforProcessExited)之外调用此事件时似乎很好但是当我从usbforProcessExited调用它时它会出错 –

object reference not set to an instance of an object

主要形式

public partial class main : Form
{
    b rsSet = new b();

    public main()
    {
        InitializeComponent();
        rsSet.SetStatusEvent += new RemoteS.SetStatus(updateStatus);
    }

    private void button1_Click(object sender,EventArgs e)
    {
        rsSet.FormatUSB();
    }

    private delegate void UpdateStatus(int i,string str,Color clr);

    private void SetStatus(int i,Color clr)
    {
        this.progressBar1.Value = i;
        this.lbl_status.ForeColor = clr;
        this.lbl_status.Text = str;
    }

    private void updateStatus(int i,String msg,Color color)
    {
        object[] p = GetInokerPara(i,msg,color);
        BeginInvoke(new UpdateStatus(SetStatus),p);
    }

    private object[] GetInokerPara(int progress,string msg,Color color)
    {
        object[] para = new object[3];
        para[0] = progress;
        para[1] = msg;
        para[2] = color;

        return para;
    }
}

b级

class b
{
    public delegate void SetStatus(int i,Color color);
    public event SetStatus SetStatusEvent;

    System.Diagnostics.Process usbfor = new System.Diagnostics.Process();

    public void FormatUSB()
    {

        usbfor.StartInfo.FileName = @"usbformat.bat";
        usbfor.EnableRaisingEvents = true;
        usbfor.Exited += new EventHandler(usbforProcessExited);
        usbfor.Start();
    }

    public void usbforProcessExited(object sender,EventArgs f)
    {
        SetStatusEvent(100,"DONE",Color.Green); //ERROR HERE! (object reference not set to an instance of an object
    }
}

问题出在哪儿?

解决方法

你有一个竞争条件:

usbforProcessExited在b的构造函数中被订阅,并且可能在调用rsSet.SetStatusEvent = new RemoteS.SetStatus(updateStatus)之前调用.

您只应在订阅SetStatusEvent后调用usbfor.Start().

一个相关的问题是该事件将在另一个线程上运行.您应该在启动进程之前设置rsSet.SynchronizingObject,以便您的事件处理程序可以修改表单而无需手动调用Invoke / BeginInvoke.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读