How to create a thread?
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
The following ways work.
// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));
// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
StartupB(port, path);
});
t2.Start();
// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();
The Startup methods have following signature for these examples.
public void StartupA(object parameters);
public void StartupB(int port, string path);
Update The currently suggested way to start a Task is simply using Task.Run()
Task.Run(() => foo());
Note that this method is described as the best way to start a task see here
Previous answer
I like the Task Factory from System.Threading.Tasks. You can do something like this:
Task.Factory.StartNew(() =>
{
// Whatever code you want in your thread
});
Note that the task factory gives you additional convenience options like ContinueWith:
Task.Factory.StartNew(() => {}).ContinueWith((result) =>
{
// Whatever code should be executed after the newly started thread.
});
Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.