Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spawn thread in C#

Could anyone please give a sample or any link that describes how to spawn thread where each will do different work at the same time.

Suppose I have job1 and job2. I want to run both the jobs simultaneously. I need those jobs to get executed in parallel. how can I do that?

like image 979
deepak Avatar asked Apr 18 '10 06:04

deepak


People also ask

Can you create threads in C?

Thread functions in C/C++ In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow.

What are threads in C?

Threads/ Processes are the mechanism by which you can run multiple code segments at a time, threads appear to run concurrently; the kernel schedules them asynchronously, interrupting each thread from time to time to give others chance to execute.

Is printf thread safe in C?

the standard C printf() and scanf() functions use stdio so they are thread-safe.

Is C single threaded?

I was recently reading "The C Programming language" by Ritchie, I noticed that C is a single threaded language.


2 Answers

Well, fundamentally it's as simple as:

ThreadStart work = NameOfMethodToCall;
Thread thread = new Thread(work);
thread.Start();
...

private void NameOfMethodToCall()
{
    // This will be executed on another thread
}

However, there are other options such as the thread pool or (in .NET 4) using Parallel Extensions.

I have a threading tutorial which is rather old, and Joe Alabahari has one too.

like image 66
Jon Skeet Avatar answered Oct 05 '22 13:10

Jon Skeet


Threading Tutorial from MSDN!

http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx

like image 34
Mahesh Velaga Avatar answered Oct 05 '22 14:10

Mahesh Velaga