Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading in c#

How to call a function which takes two parameters using threading in C#? I have to call StartDNIThread(string storeID, string queryObject) from another function.I have to pass the two values.Both are string

like image 917
Janmejay Avatar asked Sep 04 '09 13:09

Janmejay


People also ask

What is threading in C?

Thread-based multitasking deals with the concurrent execution of pieces of the same program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Why we are using threads in C?

Threads operate faster than processes due to following reasons: 1) Thread creation is much faster. 2) Context switching between threads is much faster. 4) Communication between threads is faster.

Do we have threads in C?

Yes you can use threads with C and there are various libraries you can use to do this, pthreads being one of them.


1 Answers

Your options are:

  • Encapsulate the parameters in a new class, and put the method to use for the delegate into that class.
  • Use anonymous functions (anonymous methods or lambda expressions) to do the same thing automatically with captured variables.

The latter is generally easier of course. You haven't shown what you're doing with the thread, but you might do something like:

string storeID = "...";
string queryObject = "...";

Thread t = new Thread(() => StartDNIThread(storeID, queryObject));
t.Start();

Note that because the variables are captured, you shouldn't change the values until after you know the thread has actually started. You can work around this by using captured variables only used by the anonymous function:

string storeID = "...";
string queryObject = "...";

string storeIDCopy = storeID;
string queryObjectCopy = queryObject;
Thread t = new Thread(() => StartDNIThread(storeIDCopy, queryObjectCopy));
t.Start();
// You can now change storeID and queryObject freely

This is particularly important if you're doing anything in a loop, as the loop variables themselves will change. For example:

foreach (string storeID in stores)
{
    string storeIDCopy = storeID;
    Thread t = new Thread(() => StartDNIThread(storeIDCopy, queryObject));
    t.Start();
}

If you're using the thread pool or any other way of starting threads, the pattern is basically the same.

like image 175
Jon Skeet Avatar answered Sep 26 '22 13:09

Jon Skeet