首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

c#未处理错误有关问题

2012-05-30 
c#未处理异常问题[codeC#][/code]using Systemusing System.Collections.Genericusing System.Componen

c#未处理异常问题
[code=C#][/code]  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
   
  int i;
  Thread thread1; //创建线程
  delegate void set_text(string s); //创建委托
  set_text a;
  public Form1()
  {
  InitializeComponent();
  }

  private void Form1_KeyDown(object sender, KeyEventArgs e)
  {

  }
   
  private void _start(object sender, EventArgs e)
  {
  thread1 = new Thread(new ThreadStart(run));
  thread1.Start();
  }
   
  private void run()
  {
  for (i = 0; i <= 50; i++)
  {
  num_in.Invoke(a, i.ToString());
  Thread.Sleep(200);
  }
  }
  private void set_text1(string s)
  {
  num_in.Text = s;

  }
   
  private void Form1_Load(object sender, EventArgs e)
  {
  num_in.Text = "0";
  a = new set_text(set_text1);
  }

  private void exit_Click(object sender, EventArgs e)
  {
  // this.Close();
  }

  private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  {
   
  if (thread1.IsAlive)
  thread1.Abort();
  }
  }
}


程序退出时提示未处理异常:
未处理 System.NullReferenceException
  Message=未将对象引用设置到对象的实例。

初学c#,不太理解,求高手!!!!!




[解决办法]
先是 Form 实例销毁了, Control.Invoke 会导致这个异常。

num_in.Invoke(a, i.ToString()); 之前判断下 Form 是否 Disposed
[解决办法]

C# code
private void Form1_FormClosed(object sender, FormClosedEventArgs e){    if (thread1 != null)//判空一下    {        if (thread1.IsAlive)            thread1.Abort();    }} 

热点排行