以下のコードで myForm_FormClosing の後に timer_Tick を呼び出す可能性はありますか?
可能性がある場合: myForm_FormClosing の後に timer_Tick が呼び出されるのを避けるために、myForm_FormClosing 内で timer.Stop() を呼び出すだけで十分ですか?
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace Test
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private IContainer components;
private Timer timer;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public MyForm()
{
components = new Container();
timer = new Timer(components);
timer.Interval = 50;
timer.Tick += timer_Tick;
timer.Enabled = true;
FormClosing += myForm_FormClosing;
}
private void timer_Tick(object sender, EventArgs e)
{
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
更新:いくつかのヒントを受け取った後(助けてくれてありがとう)、基本的に次のコードを選択して、必要なものを達成しました。myForm_FormClosing が呼び出された後でも timer1_Tick が呼び出される可能性があることに注意してください。このソリューションは、myForm_FormClosing が呼び出された後に実行される timer1_Tick 内のコードを停止するフラグ (私は doWork と呼びます) を導入するだけです。
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace Test
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private IContainer components;
private Timer timer;
private bool doWork = true;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public MyForm()
{
components = new Container();
timer = new Timer(components);
timer.Interval = 50;
timer.Tick += timer_Tick;
timer.Enabled = true;
FormClosing += myForm_FormClosing;
}
private void timer_Tick(object sender, EventArgs e)
{
if (doWork)
{
//do the work
}
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
doWork = false;
}
}
}