|
 |
|
WinApp C# ช่วยหน่อยครับ ผมใช้งาน RunWorkerAsync(object ) ใน BackgroundWorker ไม่เป็นครับ |
|
 |
|
|
 |
 |
|
ตัวอย่างพอได้ม่ะ
ทำให้หน้าจอไม่ค้างในขณะทำงานด้วย BackgroundWorker
|
 |
 |
 |
 |
Date :
2017-08-25 17:20:58 |
By :
mr.win |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (C#)
DateTime dt;
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
for (int i = 1; i < 10; i++)
new System.Threading.Thread(new System.Threading.ThreadStart(Run_2)).Start();
}
void Run_2()
{
int max = new Random().Next(500, 10000);
for (int i = 1; i <max; i++)
{
this.richTextBox1.Invoke(new Action(() => { this.richTextBox1.Text += "\n max:" +max +" tor " + i; }));
System.Threading.Thread.Sleep(100);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Invoke(new Action(() => { this.Text = "time:"+ (DateTime.Now-dt).ToString(@"hh\:mm\:ss"); }));
}
private void button2_Click(object sender, EventArgs e)
{
dt = DateTime.Now;
backgroundWorker1.RunWorkerAsync();
}
ถ้าเราใช้
Code (C#)
new System.Threading.Thread(new System.Threading.ThreadStart(Run_2)).Start();
จะทำงาน หลายๆ Thread ได้ แต่
Code (C#)
this.Invoke(new Action(() => { this.Text = "time:"+ (DateTime.Now-dt).ToString(@"hh\:mm\:ss"); }));
จะทำงานไม่ตรง คือมันทำงานหลัง
Code (C#)
for (int i = 1; i < 10; i++)
new System.Threading.Thread(new System.Threading.ThreadStart(Run_2)).Start();
ทั้งๆที่ Run_2 ยังทำงานไม่เสร็จเลย
แต่ถ้าใช้
Code (C#)
Run_2();
จะสามารถใช้งาน
Code (C#)
this.Invoke(new Action(() => { this.Text = "time:"+ (DateTime.Now-dt).ToString(@"hh\:mm\:ss"); }));
ผมอยากได้โค้ดที่ทำงานแยก thread กัน แต่ก็ประมวลผลโดยรวมได้ พอจะมีตัวอย่างไม๊ครับ
|
 |
 |
 |
 |
Date :
2017-08-26 15:53:08 |
By :
lamaka.tor |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|
|

|
Load balance : Server 03
|