如何将参数和方法一起发送到新线程
本文关键字:新线程 线程 参数 一起 方法 | 更新日期: 2023-09-27 18:29:05
目前,我正在工作:
public void logowanie()
{
int x=5,y=5;
...
}
private void button2_Click(object sender, EventArgs e)
{
Thread thread2 = new Thread(new ThreadStart(logowanie));
thread2.Start();
//logowanie("xd", "xd", "xd");
}
这是有效的。有可能制造类似的东西吗
public int logowanie(int x, int y)
{
...
}
private void button2_Click(object sender, EventArgs e)
{
Thread thread2 = new Thread(new ThreadStart(logowanie(5,5)));
thread2.Start();
//logowanie("xd", "xd", "xd");
}
我刚开始穿线。感谢
虽然可以使用ParameterizedThreadStart
,但我可能只使用lambda表达式:
private void button2_Click(object sender, EventArgs e)
{
Thread thread2 = new Thread(() => logowanie(5, 5));
thread2.Start();
}
请注意,如果在循环中调用此函数,则需要小心,因为lambda表达式捕获变量的方式如下:
// Broken (before C# 5)
foreach (string url in urls)
{
new Thread(() => CrawlUrl(url));
}
// Fixed
foreach (string url in urls)
{
string copy = url;
new Thread(() => CrawlUrl(copy));
}
这只是在某些情况下的一个问题,即您正在捕获一个变量,并且确实想捕获当前值,但这是值得了解的。
您可以使用ParameterizedThreadStart
并将对象传递给线程:
class ParametersForThread
{
public int x;
public int y;
}
...
Thread thread2 = new Thread(new ParameterizedThreadStart(logowanie));
thread2.Start(new ParametersForThread() { x = 5, y = 5 });
你的线程方法必须看起来像
void logowanie(object state)
{
ParametersForThread parameters = state as ParametersForThread;
....;
}
创建一个新的类或结构。传递并投射。
或者您可以使用内联代码,参数将自动传递给新线程。
void method()
{
int a = 5, b = 6;
Thread t = new Thread(delegate()
{
CallOtherMethodOnTheNewThread(a, b);
});
t.Start();
}
使用委托。你可以定义自己的,也可以使用内置的通用方法,如Action、Action(T),或者在你的情况下,Action(T1,T2)
private Action<int,int> myLoggingDelegate;
private void button2_Click(object sender, EventArgs e)
{
myLoggingDelegate = logowanie;
myLoggingDelegate.BeginInvoke(myParam1,myParam2,Callback,null); //this is aynchronous
}
private void Callback(IAsyncResult ar)
{
myLoggingDelegate.EndInvoke(ar);
}
步骤1:创建一个类来组合单个对象上的参数:
private class ThreadParams {
public int X { get; set; }
public int Y { get; set; }
public ThreadParams(int x, int y)
{
this.X = x;
this.Y = y;
}
}
步骤2:在你的方法上声明这个对象:
public void logowanie(ThreadParams param)
{
...
}
步骤3:使用ParameterizedThreadStart:发送值
Thread thread = new Thread(new ParameterizedThreadStart(logowanie));
ThreadParams prm = new ThreadParams(5,5);
thread.Start(prm);