using System; using System.Windows.Forms; using System.Threading; class MainForm : Form { TextBox textBox; Thread thread; volatile bool abortRequest = false; volatile bool activeBackground = false; void DoBackgroundWork() { activeBackground = true; while (!abortRequest) { Thread.Sleep(1000); this.BeginInvoke(new EventHandler((sender, e) => { textBox.AppendText("."); }), new object [] { this, EventArgs.Empty }); } this.Invoke(new EventHandler((sender, e) => { textBox.AppendText(Environment.NewLine + "UI同期が必要な終了処理"); activeBackground = false; this.Close(); }), new object [] { this, EventArgs.Empty }); } public MainForm() { thread = new Thread(DoBackgroundWork); textBox = new TextBox() { Multiline= true, Dock = DockStyle.Fill }; this.Controls.Add(textBox); this.Load += (sender, e) => { thread.Start(); }; this.Closing += (sender, e) => { if (activeBackground) { abortRequest = true; e.Cancel = true; } }; } } class Program { static void Main() { Application.Run(new MainForm()); } }