Wielowątkowość w Windows Forms.pdf

(241 KB) Pobierz
WIELOWĄTKOWOŚĆ W WINDOWS FORMS
Threat 1 – Używamy Sleep
Kontrolki:
Button x 3, RichTextBox x 1
Wygląd programu:
Cały kod:
public partial class
Form1
: Form
{
public
Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
}
private void
button1_Click(object sender, EventArgs e)
{
richTextBox1.Text =
string.Empty;
for
(int i = 0; i < 100; i++)
{
richTextBox1.AppendText(i +
", ");
// using System.Threading;
Thread.Sleep(100);
}
}
private void
button2_Click(object sender, EventArgs e)
{
richTextBox1.Text = MyMethod1(100);
}
Wielowątkowość w Windows Forms
1
string
MyMethod1(int i)
{
string
s =
string.Empty;
for
(i = 0; i < 100; i++)
{
s = s + i +
", ";
Thread.Sleep(100);
}
}
return
s;
}
private void
button3_Click(object sender, EventArgs e)
{
richTextBox1.Text =
string.Empty;
}
Wygląd programu po uruchomieniu:
Wielowątkowość w Windows Forms
2
Task 1 – Run
Kontrolki:
Button x 3, RichTextBox x 1
Wygląd programu:
Cały kod:
public partial class
Form1
: Form
{
public
Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
}
private void
button1_Click(object sender, EventArgs e)
{
richTextBox1.Text =
string.Empty;
var
task = Task.Run(() =>
{
return
457.89;
});
}
richTextBox1.AppendText(task.Result.ToString());
Wielowątkowość w Windows Forms
3
private void
button2_Click(object sender, EventArgs e)
{
richTextBox1.Text =
string.Empty;
var
task = Task.Run(() =>
{
string
s =
string.Empty;
for
(int i = 0; i < 100; i++)
{
s = s + i +
", ";
}
return
s;
Thread.Sleep(100);
});
}
richTextBox1.AppendText(task.Result);
}
private void
button3_Click(object sender, EventArgs e)
{
richTextBox1.Text =
string.Empty;
}
Wygląd programu po uruchomieniu:
Wielowątkowość w Windows Forms
4
Task 2 – Run
Kontrolki:
Button x 3, RichTextBox x 1
Wygląd programu:
Cały kod:
public partial class
Form1
: Form
{
public
Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
}
private void
button1_Click(object sender, EventArgs e)
{
richTextBox1.Text =
string.Empty;
var
tasks =
new
Task[4];
var
result =
new int[4];
tasks[0]
tasks[1]
tasks[2]
tasks[3]
=
=
=
=
Task.Run(()
Task.Run(()
Task.Run(()
Task.Run(()
=>
=>
=>
=>
result[0]
result[1]
result[2]
result[3]
=
=
=
=
5);
15);
25);
35);
Task.WaitAll(tasks);
foreach
(var item
in
result)
{
richTextBox1.AppendText(item +
", ");
}
}
Wielowątkowość w Windows Forms
5
Zgłoś jeśli naruszono regulamin