handle dispose in FormTask

This commit is contained in:
test 2019-05-03 15:36:43 +02:00
parent 1568e5ea49
commit e00f16b679
2 changed files with 35 additions and 9 deletions

View File

@ -60,6 +60,8 @@
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();

View File

@ -19,12 +19,16 @@ namespace WindowsFormsAppTask
InitializeComponent();
}
private Task t;
private CancellationTokenSource cts;
private void Button1_Click(object sender, EventArgs e)
{
var t = new Task(DoIt);
cts = new CancellationTokenSource();
t = new Task(DoIt, cts.Token);
t.Start();
for (int i = 0; i < 999; i++)
for (var i = 0; i < 999; i++)
{
textBox1.Text += "-";
Application.DoEvents(); //update ui elements
@ -37,24 +41,44 @@ namespace WindowsFormsAppTask
{
//Console.WriteLine(".");
for (int i = 0; i < 999; i++)
for (var i = 0; i < 999; i++)
{
if (textBox1.InvokeRequired)
if (cts.IsCancellationRequested)
{
textBox1.Invoke(new MethodInvoker(() => { textBox1.Text += "x"; }));
return;
}
else
try
{
textBox1.Text += "x";
if (textBox1.InvokeRequired)
textBox1.Invoke(new MethodInvoker(() => { textBox1.Text += "x"; }));
else
textBox1.Text += "x";
}
catch (ObjectDisposedException)
{
return;
}
Random random = new Random();
Thread.Sleep(random.Next(100, 500));
Thread.Sleep(200);
}
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
cts.Cancel();
for (var i = 0; i < 999; i++)
{
var ii = 0;
}
}
}
}