Make Thread-Safe Calls to Windows Forms Controls (2009-12-28)
ตัวอย่างนี้ผมให้ thread เขียน TextBox นะครับ ทดสอบแล้วใช้งานได้ครับ แต่ code อาจจะไม่ค่อยดีนะครับ
ชี้แนะได้นะครับ
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace TestThread
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
public Form1()
{
InitializeComponent();
}
class MyObject
{
public string myName;
public TextBox txtbox;
public MyObject(ref TextBox txtBox)
{
this.txtbox = txtBox;
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtbox.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
txtbox.Invoke(d, new object[] { text });
}
else
{
this.txtbox.Text = text;
}
}
public void Start()
{
while (true)
{
Mutex objMutex = new Mutex(false, "ThreadLock");
try
{
objMutex.WaitOne();
//Console.WriteLine("I am >> " + this.myName);
//this.txtbox.Text = "I am >> " + this.myName;
this.SetText("I am >> " + this.myName);
}
finally
{
objMutex.ReleaseMutex();
}
Random random = new Random();
Thread.Sleep(random.Next(1000, 3000));
}
}
}
private void button1_Click(object sender, EventArgs e)
{
MyObject obj = new MyObject(ref this.textBox1);
obj.myName = "Chiwa";
Thread thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
obj = new MyObject(ref this.textBox1);
obj.myName = "Pee";
thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
obj = new MyObject(ref this.textBox1);
obj.myName = "Nok";
thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|