Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a thread?

The method below is what I want to be done in that thread:

public void Startup(int port,string path) {     Run(path);     CRCCheck2();     CRCCheck1();     InitializeCodeCave((ushort)port); } 

I tried what I could find googling,but nothing worked

public void Test(int port,string path) {     Thread t = new Thread(Startup(port,path)); }  public void TestA(int port,string path) {     Thread t = new Thread(Startup);     t.Start (port,path); } 

Both don't compile,how to do that?

like image 508
Ivan Prodanov Avatar asked May 01 '09 12:05

Ivan Prodanov


People also ask

How can we create thread?

A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called. The Main thread in Java is the one that begins executing when the program starts.

What does it mean create a thread?

Discord introduced Threads, temporary text channels that will automatically disappear after they have been inactive for a specific length of time. You can create a Thread using any existing message, as well as from scratch. This feature allows you to organize different conversations within a single channel.


2 Answers

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); 
like image 135
Mikko Rantanen Avatar answered Sep 29 '22 13:09

Mikko Rantanen


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.

like image 20
anhoppe Avatar answered Sep 29 '22 14:09

anhoppe