Reputation: 3152
At the moment, I've got working:
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");
}
And that works. Is it possible to make something like
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");
}
I've just started with threading things. Thanks
Upvotes: 2
Views: 138
Reputation: 2503
Step 1: create a class to combine parameters on a single object:
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;
}
}
Step 2: declare this object on your method:
public void logowanie(ThreadParams param)
{
...
}
Step 3: send the values with ParameterizedThreadStart:
Thread thread = new Thread(new ParameterizedThreadStart(logowanie));
ThreadParams prm = new ThreadParams(5,5);
thread.Start(prm);
Upvotes: 0
Reputation: 45135
Use a delegate. You can either define your own or use one of the built-in general purpose ones like Action, Action(T) or, in your case 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);
}
Upvotes: 0
Reputation: 755
Or you can use inline code, the parameters will be automatically passed to the new thread.
void method()
{
int a = 5, b = 6;
Thread t = new Thread(delegate()
{
CallOtherMethodOnTheNewThread(a, b);
});
t.Start();
}
Upvotes: 0
Reputation: 1500785
While you could use ParameterizedThreadStart
, I'd probably just use a lambda expression:
private void button2_Click(object sender, EventArgs e)
{
Thread thread2 = new Thread(() => logowanie(5, 5));
thread2.Start();
}
Note that if you call this in a loop, you'll need to be careful because of the way that variables are captured by lambda expressions:
// 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));
}
This is only an issue in certain situations where you're capturing a variable and really want to capture the current value instead, but it's worth knowing about.
Upvotes: 5
Reputation: 56697
You can use ParameterizedThreadStart
and pass an object to the thread:
class ParametersForThread
{
public int x;
public int y;
}
...
Thread thread2 = new Thread(new ParameterizedThreadStart(logowanie));
thread2.Start(new ParametersForThread() { x = 5, y = 5 });
Your thread method must look like
void logowanie(object state)
{
ParametersForThread parameters = state as ParametersForThread;
....;
}
Upvotes: 2