前提・実現したいこと
C#でWindowsフォームの開発をしています。
今やりたいことは
1.フォーム上にボタンが2つ [button_A]と[button_B] がある。
2.[button_A]を押すと、処理が走る(例えば、DB接続やファイル書込)
3.(2)の処理中に[button_A]と[button_B]のクリックイイベントを動かないようにする。
ただし、ボタン非活性(enableプロパティ=true)は行わない。
発生している問題・エラーメッセージ
[button_A]の実行中に[button_A]や[button_B]をクリックすると、
[button_A]の処理後にイベントが実行されてしまう。(イベントがメモリ上に残ってしまう)
試したこと
イベント破棄をするために、
this.button1.Click += new System.EventHandler(this.button1_Click);
を実装したが、うまくいかない
// Form1.cs namespace TestSample { public partial class Form1 : Form { private int isProcessing; public Form1() { isProcessing = 0; InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if(isProcessing == 1) { return; } isProcessing = 1; this.button1.Click -= new System.EventHandler(this.button1_Click); this.button2.Click -= new System.EventHandler(this.button2_Click); // テキストに数字を出力(テスト用で簡易なロジック実装) DataOutPut dataOutPut = new DataOutPut("[start]", "[end]"); dataOutPut.OutPutFile(); isProcessing = 0; Application.DoEvents(); this.button1.Click += new System.EventHandler(this.button1_Click); this.button2.Click += new System.EventHandler(this.button2_Click); return; } private void button2_Click(object sender, EventArgs e) { this.Close(); return; } private void Form1_Closing(object sender, FormClosingEventArgs e) { if (isProcessing == 1) { Console.WriteLine("★ -- No Form1_Closing() -- ★"); e.Cancel = true; } } } }
// DataOutPut.cs namespace TestSample { class DataOutPut { private string startCode; private string endCode; public DataOutPut(string startCode, string endCode) { this.startCode = startCode; this.endCode = endCode; } // テキストファイルに出力 public int OutPutFile() { string filePath = @"C:\Users\fujiwarak\Desktop\work\"; string fileName = "test_"; string dt = (DateTime.Now).ToString("yyyyMMddHHmmss"); Encoding enc = Encoding.GetEncoding("Shift_JIS"); int index = 0; while (index < 3) { string filePathName = filePath + fileName + index.ToString() + dt + ".txt"; using (StreamWriter writer = new StreamWriter(filePathName, true)) { writer.WriteLine(startCode); int loop = 0; int number = 0; while (loop <= 10) { System.Threading.Thread.Sleep(1000); writer.WriteLine(number.ToString()); number++; loop++; } writer.WriteLine(endCode); } index++; } return 0; } } }