1

2 番目の形式でのメッセージの非同期出力。2 番目のフォームを閉じるときに、System.Windows.Forms.dll で System.ObjectDisposedException が発生しました。

MainForm は SecondForm を実行します。SecondForm は、メッセージ ジェネレータと、テキスト ボックス内のメッセージの印刷の非同期スレッドを実行します。メッセージ ジェネレーターは、ランダムな時間遅延でメッセージを作成します。文字列形式の遅延時間はこのメッセージです。問題 - 2 番目のフォーム、メソッド 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