摘要
啟動線程的時候需要向線程函數中傳遞參數,一般有三種方式。
正文
用object 傳參數
private void btnStart_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(ShowDot);
t1.Start(10);
}
void ShowDot(object max)
{
int imax=int.Parse(max.ToString());
for (int i = 0; i < imax; i++)
{
this.BeginInvoke((() =>
{
txtValue.Text += ".";
}));
System.Threading.Thread.Sleep(10);
}
}
通過lambda
private void btnStart_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(() => { ShowDot(10); });
t1.Start();
}
void ShowDot(int max)
{
for (int i = 0; i < max; i++)
{
this.BeginInvoke((() =>
{
txtValue.Text += ".";
}));
System.Threading.Thread.Sleep(10);
}
}
使用類封裝
public class Dot
{
TextBox txt;
int max = 0;
public Dot(int max, TextBox txt)
{
this.max = max;
this.txt = txt;
}
public void ShowDot()
{
for (int i = 0; i < max; i++)
{
txt.BeginInvoke((() =>
{
txt.Text += ".";
}));
System.Threading.Thread.Sleep(10);
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
Dot d = new Dot(10, txtValue);
Thread t1 = new Thread(d.ShowDot);
t1.Start();
}
可以使用lock關鍵字來進行加鎖操作
如果鎖定了一個對象,需要訪問該對象的所有其他線程則會處于阻塞狀態,并等待直到該對象解除鎖定。這,可能會導致嚴重的性能問題。
public class Dot
{
private readonly object lockObj = new object();
TextBox txt;
int max = 0;
public Dot(int max, TextBox txt)
{
this.max = max;
this.txt = txt;
}
public void ShowDot()
{
lock (lockObj)
{
for (int i = 0; i < max; i++)
{
txt.BeginInvoke((() =>
{
txt.Text += ".";
}));
System.Threading.Thread.Sleep(10);
}
}
}
}
該文章在 2024/3/31 1:10:28 編輯過