【C#】线程中参数传递
|
admin
2024年3月31日 1:9
本文热度 657
|
摘要
启动线程的时候需要向线程函数中传递参数,一般有三种方式。
正文
用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 编辑过