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
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.
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.
Yes you can use threads with C and there are various libraries you can use to do this, pthreads being one of them.
Your options are:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With