1

以第二种形式异步打印消息。关闭第二个表单期间 System.Windows.Forms.dll 中的 System.ObjectDisposedException。

MainForm 运行 SecondForm。SecondForm 运行消息生成器和在文本框中打印消息的异步线程。消息生成器创建具有随机时间延迟的消息。字符串格式的时间延迟就是这个消息。问题 - 在关闭第二个表单时,方法 SecondForm_Closing,我收到异常

无法访问已处置的对象期间 System.Windows.Forms.dll 中的 System.ObjectDisposedException。

public partial class MainForm : Form
{
    secondForm SecondForm;
    private void MainForm_Closing(object o, FormClosingEventArgs e)
    {
        Environment.Exit(0);
    }
    public MainForm()
    {
        InitializeComponent();
        SecondForm = new secondForm();
        SecondForm.Show();
    }
}
public partial class secondForm : Form
{
    private messageGenerator MessageGenerator;
    Action actPrint;
    //This method calls ObjectDisposedException then point to Invoke in method Print
    private void SecondForm_Closing(object o, FormClosingEventArgs e)
    {
        Close();
    }
    public secondForm()
    {
        InitializeComponent();
        MessageGenerator = new messageGenerator();
        actPrint = new Action(Print);
        actPrint.BeginInvoke(null, null);
    }
    public void Print()
    {
        while (true)   //  Infinite  cycle
        {
            MessageGenerator.CreateEvent.WaitOne(); //  Wait event "Message is created"
            MessageGenerator.CreateEvent.Reset();//  Event reset
            Invoke(new MethodInvoker
            (() =>
            {
                TextBoxTimeDelay.Text = MessageGenerator.Message;//  Message print
            }));
        }
    }
}
public class messageGenerator
{
    public AutoResetEvent CreateEvent;
    public string Message;
    public Action actStart;
    public messageGenerator()
    {
        CreateEvent = new AutoResetEvent(false);
        actStart = new Action(Start);
        actStart.BeginInvoke(null, null);
    }
    public void Start()
    {
        Random R = new Random();
        while (true)
        {
            int TimeDelay = 10 * R.Next(1, 5);
            Thread.Sleep(TimeDelay);
            Message = TimeDelay.ToString();
            CreateEvent.Set();  //  Event "Message is created"
        }
    }
}

这里开始的解决方案没有实现资源。即 MessageGenerator 继续,并且 Print 方法工作。如何实现资源?

private void SecondForm_Closing (object o, FormClosingEventArgs e)
{
    e.Cancel = true;
    this.Hide();
    this.Parent = null;
}
4

0 回答 0