forked from michaeledore/ThreadingInCSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
81 lines (68 loc) · 2.25 KB
/
Form1.cs
File metadata and controls
81 lines (68 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ThreadingUpdateUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<Label> threadLabels = new List<Label>();
private void btnGo_Click(object sender, EventArgs e)
{
if(threadLabels.Count < 100)
{
int.TryParse(textBox1.Text, out int iteration);
int.TryParse(textBox2.Text, out int sleepDuration);
Label l = new Label();
l.Text = DateTime.Now.ToLongTimeString();
threadLabels.Add(l);
l.Top = (panel1.Controls.Count) * l.Height + 20;
l.Left = 5;
this.panel1.Controls.Add(l);
Task.Factory.StartNew(() =>
{
for (int i = 0; i <= iteration; i++)
{
this.Invoke((MethodInvoker)delegate
{
l.Text = i.ToString();
});
Thread.Sleep(sleepDuration);
}
});
}
}
private void btnGoNoThread_Click(object sender, EventArgs e)
{
int.TryParse(textBox1.Text, out int iteration);
int.TryParse(textBox2.Text, out int sleepDuration);
btnGoNoThread.Enabled = false;
textBox1.Enabled = false;
textBox2.Enabled = false;
for (int i = 0; i <= iteration; i++)
{
lblCounter.Text = i.ToString();
lblCounter.Refresh();
Thread.Sleep(sleepDuration);
}
btnGoNoThread.Enabled = true;
textBox1.Enabled = true;
textBox2.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//We need to kill any running threads
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
}
}