Is there any ThreadStatic attribute for parent and child threads - c#

Is there any attribute or some method of sharing a value between a thread and the background workers it creates?
I am making a SQL Server CLR assembly that does a search in the database + some calculations, and I want it to be multi threading. I need to share some data between the calling thread and the background workers I create (what is read from the calling thread from database, I want to be passed to the workers, so that they compute what I need).
I don't think that sending a class object as parameter to the RunWorkerAsync is a good idea, since inside the threads I use lock(item); and Interlocked.Add(ref itemCount, -1); mechanism.
What I also need, is that if another search call is made, the values from these 2 call stacks are not mixed up.
Thank you!

Instead of using ThreadStatic variables like you want, you might consider passing your integer as a parameter, but instead of passing it raw, wrap it in a holder object.
class ResultHolder
{
public int result;
}
You can then use the object to hold your int by reference.
Thread t = new Thread(Run);
var holder = new ResultHolder() { result = 0x92 }
t.Start(holder);
// Query the result
Console.WriteLine(holder.result);

Related

Is it possible to modify an object passed like a parameter to other thread with C#? [duplicate]

is there any way in c# to put objects in another thread? All I found is how to actually execute some methods in another thread. What I actually want to do is to instanciate an object in a new thread for later use of the methods it provides.
Hope you can help me,
Russo
Objects do not really belong to a thread. If you have a reference to an object, you can access it from many threads.
This can give problems with object that are not designed to be accessed from many threads, like (almost all) System.Windows.Forms classes, and access to COM objects.
If you only want to access an object from the same thread, store a reference to the thread in the object (or a wrapping object), and execute the methods via that thread.
There seems to be some confusion about how threads work here, so this is a primer (very short too, so you should find more material before venturing further into multi-threaded programming.)
Objects and memory are inherently multi-thread in the sense that all threads in a process can access them as they choose.
So objects do not have anything to do with threads.
However, code executes in a thread, and it is the thread the code executes in that you're probably after.
Unfortunately there is no way to just "put an object into a different thread" as you put it, you need to specifically start a thread and specify what code to execute in that thread. Objects used by that code can thus be "said" to belong to that thread, though that is an artificial limit you impose yourself.
So there is no way to do this:
SomeObject obj = new SomeObject();
obj.PutInThread(thatOtherThread);
obj.Method(); // this now executes in that other thread
In fact, a common trap many new multi-thread programmers fall into is that if they create an object in one thread, and call methods on it from another thread, all those methods execute in the thread that created the object. This is incorrect, methods always executes in the thread that called them.
So the following is also incorrect:
Thread 1:
SomeObject obj = new SomeObject();
Thread 2:
obj.Method(); // executes in Thread 1
The method here will execute in Thread 2. The only way to get the method to execute in the original thread is to cooperate with the original thread and "ask it" to execute that method. How you do that depends on the situation and there's many many ways to do this.
So to summarize what you want: You want to create a new thread, and execute code in that thread.
To do that, look at the Thread class of .NET.
But be warned: Multi-threaded applications are exceedingly hard to get correct, I would not add multi-threaded capabilities to a program unless:
That is the only way to get more performance out of it
And, you know what you're doing
All threads of a process share the same data (ignoring thread local storage) so there is no need to explicitly migrate objects between threads.
internal sealed class Foo
{
private Object bar = null;
private void CreateBarOnNewThread()
{
var thread = new Thread(this.CreateBar);
thread.Start();
// Do other stuff while the new thread
// creates our bar.
Console.WriteLine("Doing crazy stuff.");
// Wait for the other thread to finish.
thread.Join();
// Use this.bar here...
}
private void CreateBar()
{
// Creating a bar takes a long time.
Thread.Sleep(1000);
this.bar = new Object();
}
}
All threads can see the stack heap, so if the thread has a reference to the objects you need (passed in through a method, for example) then the thread can use those objects. This is why you have to be very careful accessing objects when multi-threading, as two threads might try and change the object at the same time.
There is a ThreadLocal<T> class in .NET that you can use to restrict variables to a specific thread: see http://msdn.microsoft.com/en-us/library/dd642243.aspx and http://www.c-sharpcorner.com/UploadFile/ddoedens/UseThreadLocals11212005053901AM/UseThreadLocals.aspx
Use ParameterizedThreadStart to pass an object to your thread.
"for later use of the methods it provides."
Using a class that contains method to execute on new thread and other data and methods, you can gain access from your thread to Data and methods from the new thread.
But ... if your execute a method from the class, you are executing on current thread.
To execute the method on the new thread needs some Thread syncronization.
System.Windows.Forms.Control.BeginInvoke do it, the Control thread is waiting until a request arrives.
WaitHandle class can help you.
There's a lot of jargon around threading, But it boils down something pretty simple.
For a simple program, you have one point of execution flowing from point a to b, one line at a time. Programming 101, right?
Ok, for multithreading, You now have more then one point of execution in your program. So, point 1 can be in one part of your program, and point 2 can be someplace else.
It's all the same memory, data and code, but you have more then one thing happening at a time. So, you can think, what happens of both points enter a loop at the same time, what do you think would happen? So techniques were created to keep that kind of issue either from happening, or to speed up some kind of process. (counting a value vs. say, networking.)
That's all it really is. It can be tricky to manage, and and it's easy to get lost in the jargon and theory, but keep this in mind and it will be much simpler.
There are other exceptions to the rule as always, but this is the basics of it.
If the method that you run in a thread resides in a custom class you can have members of this class to hold the parameters.
public class Foo
{
object parameter1;
object parameter2;
public void ThreadMethod()
{
...
}
}
Sorry to duplicate some previous work, but the OP said
What I actually want to do is to instanciate an object in a new thread for later use of the methods it provides.
Let me interpret that as:
What I actually want to do is have a new thread instantiate an object so that later I can use that object's methods.
Pray correct me if I've missed the mark. Here's the example:
namespace silly
{
public static class Program
{
//declared volatile to make sure the object is in a consistent state
//between thread usages -- For thread safety.
public static volatile Object_w_Methods _method_provider = null;
static void Main(string[] args)
{
//right now, _method_provider is null.
System.Threading.Thread _creator_thread = new System.Threading.Thread(
new System.Threading.ThreadStart(Create_Object));
_creator_thread.Name = "Thread for creation of object";
_creator_thread.Start();
//here I can do other work while _method_provider is created.
System.Threading.Thread.Sleep(256);
_creator_thread.Join();
//by now, the other thread has created the _method_provider
//so we can use his methods in this thread, and any other thread!
System.Console.WriteLine("I got the name!! It is: `" +
_method_provider.Get_Name(1) + "'");
System.Console.WriteLine("Press any key to exit...");
System.Console.ReadKey(true);
}
static void Create_Object()
{
System.Threading.Thread.Sleep(512);
_method_provider = new Object_w_Methods();
}
}
public class Object_w_Methods
{
//Synchronize because it will probably be used by multiple threads,
//even though the current implementation is thread safe.
[System.Runtime.CompilerServices.MethodImpl(
System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public string Get_Name(int id)
{
switch (id)
{
case 1:
return "one is the name";
case 2:
return "two is the one you want";
default:
return "supply the correct ID.";
}}}}
Just like to elaborate on a previous answer. To get back to the problem, objects and memory space are shared by all threads. So they are always shared, but I am assuming you want to do so safely and work with results created by another thread.
Firstly try one of the trusted C# patterns. Async Patterns
There are set patterns to work with, that do transmit basic messages and data between threads.
Usually the one threat completes after it computes the results!
Life threats: Nothing is fool proof when going asynchronous and sharing data on life threats.
So basically keep it as simple as possible if you do need to go this route and try follow known patterns.
So now I just like to elaborate why some of the known patters have a certain structure:
Eventargs: where you create a deepcopy of the objects before passing it. (It is not foolproof because certain references might still be shared . )
Passing results with basic types like int floats, etc, These can be created on a constructor and made immutable.
Atomic key words one these types, or create monitors etc.. Stick to one thread reads the other writes.
Assuming you have complex data you like to work with on two threads simultaneously a completely different ways to solve this , which I have not yet tested:
You could store results in database and let the other executable read it. ( There locks occur on a row level but you can try again or change the SQL code and at least you will get reported deadlocks that can be solved with good design, not just hanging software!!) I would only do this if it actually makes sense to store the data in a database for other reasons.
Another way that helps is to program F# . There objects and all types are immutable by default/ So your objects you want to share should have a constructor and no methods allow the object to get changed or basic types to get incremented.
So you create them and then they don't change! So they are non mutable after that.
Makes locking them and working with them in parallel so much easier. Don't go crazy with this in C# classes because others might follow this "convention' and most things like Lists were just not designed to be immutable in C# ( readonly is not the same as immutable, const is but it is very limiting). Immutable versus readonly

Is locking or Interlocked.Exchange required to swap a reference type field which is used in an other thread?

I know that there are .NET collections which are thread safe which I could use, but I still want to understand the following situation:
I have a Buffer class (below) which is used to writer data from a different thread, in a update loop interval (game) the main thread handles the data by swaping the list instance (to prevent both threads acting on the same instance at the same time).
So there is only a single additional thread who uses the "writerData" list, everything else is done on the main thread, but im not sure if the Swap method is thread "safe", because after searching for a while everyone seems to have a different opinion about swapping reference fields.
Some say that swapping reference doesn't require any locking other say that Interlocked.Exchange must be used in this case and other say it's not required, other say that the field must be violate and other say the keyword is "evil".
I know that threading is a difficult topic and maybe the other questions were too broad, but can someone help me to understand if any/which kind of "locking" is required in my specific case in the Swap method?
public class Buffer
{
List<byte> readerData;
List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread
// This method is only called by the other thread and it's the only method which is called from there
public void Add(byte data)
{
writerData.Add(data);
}
// Called on the main thread, before handling the readerData
public void Swap()
{
var tmp = readerData;
readerData = writerData
writerData = tmp;
}
// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}

Is it unsafe to use local variables in a call to begininvoke

I have to take over the source code of a bigger application from my colleaque that is written in C#. It uses windows forms an threads and right now it works as it should.
But one thing I am not sure about, is the way he handled parameters that are used in delegates that are raised from the thread to the windows forms in the application. I don't know why, but he defined many different object arrays with varying number of elements, eg:
private object[] delegateArray1;
private object[] delegateArray3;
private object[] delegateArray3A;
and in the code he used it then
delegateArray1 = new object[1]; // in the constructor of the thread class
delegateArray3 = new object[3];
delegateArray3a = new object[3];
// and this somewhere in the thread loop
delegateArray3[0] = systemtests.FehlerText;
delegateArray3A[1] = CheckState.Unchecked;
delegateArray3A[2] = testKanal;
sender.BeginInvoke(merkerInfoDelegate, delegateArray3);
whereby sender is the containercontrol from which the thread has been created.
merkerInfoDelegate points to a method with the signature
public void InfoAnzeige(string scrollText, CheckState state, int kanal);
The first question that I have:
Is it possible that my variables / objects that I pass to the BeginInvoke method are being garbage collected and thus are invalid when the delegate method gets finally executed. When yes, how do I prevent this from happen?
Is it not possible to call the delegate like this:
sender.BeginInvoke(merkerInfoDelegate, systemtests.FehlerText, CheckState.Unchecked, testKanal);
I would like to make the code more readable, more safe and more reliable. I think of declaring classes like the class MouseEventArgs, that consist of these parameters and that encapsulate all necessary data to be passed to the delegate method in the windows forms class...
public InfoDelegateEventArgs
{
public String Fehlertext;
public CheckState state;
public int Kanal;
}
this could be used like this:
idea = new InfoDelegateEventArgs(){...};
sender.BeginInvoke(merkerInfoDelegate, idea);
It is safe to pass "local" variables but remember they are no longer "local" once you pass them. The references have now been passed off to another operation that may be running concurrently on a separate thread. Now multiple threads have access to the "local" variable and thus it might require locking or other thread-safe treatment.
You don't need to worry about it being GC'd because there is still a reference that was passed to BeginInvoke.

Calling static method via Multiple threads - Can they meddle with each other's Input Parameters

My code gets called by AJAX UI (Multiple threads), and post data processing it sends output in Json. Recently while refactoring the code, we have shifted lot of common and repeated methods to a separate file, where we have made the them static, since we are not working on any static / shared data.
Following is a sample design our static method:
public class Helper
{
public static C Method1(List<A> aList, List<B> bList)
{
C objC = new C();
// Create ObjC based on inputs aList and bList
return objC;
}
}
Now, my understanding is that the following call will have no issue, when called in a Parallel.foreach or any other multithread scenario, please verify.
C resultC = Helper.Method1(aList, bList);
However we have doubt, can there be a rare case possible where two threads make the above mentioned call and one thread data of aList, bList, is replaced by another thread, thus giving a flawed result (may be exception), which can for that matter will be impossible to debug and repeat, since two threads have to go / execute together in precise milli seconds that method takes to execute
Please share your view are we on right track to create the above mentioned design or there are pits that we are not able to see. We can easily replace by instance method, they are surely thread safe in this scenario, since each thread has its own instance to work with, but I feel that may not be required and its troublesome to keep creating instance, when we can conveniently work with a static call.
Please note till now I haven't seen an issue with code running, but as I said if this ever happens it will be corner case, for two threads to come at same time and one thread replace the input parameter while other thread is still processing result.
The short answer to your question is no, as long as you pass in different List instances across all your different threads. .NET handles threading fine, and in itself won't get itself into a tangle, it's only if your code encourages it to do so can things get messy.
The way things get mixed up is by sharing state across different threads. So as an example, having a static method you may think it a good idea to use a static variable somewhere:
private static int count;
public static void MyMethod() {
count = count + 1;
if(count == 5) {
console.log("Equal to 5");
}
};
This sort of method is not thread safe because count can be modified by two different threads at the same time. In fact it's possible that count could be incremented to 5, and then another thread increment it to 6 before the if check, therefore you'd never log anything - which would obviously be a bit confusing.
The other way you can share state, is if you pass something in, hence my caveat at the start of the answer. If you pass the same object into the method from multiple threads this object should ideally be immutable so in your case a collection that can't be modified. This prevents the internals of the method modifying the object that could impact another thread. As already mentioned though, this is only a concern if you pass the same instances in, within different threads.
Method call will not interfere with other method calls from different thread. You have to think carefully only about static variables. Also if you share input parameters aList or bList between threads you can run into troubles.

WebService application - return new objects from static/shared method

Would using a static/shared method in a webservice application thread safe? This method would be called heavily to retrieve new instances.
For instance:
Public Shared GetPerson(ByVal name as String,ByVal surname) as Person
Dim p As New Person
p.Name = name
p.Surname = surname
p.Addresses = GetAllAddresses(name)
return p
End Function
UPDATE 1
The code posted is just a quickly typed up sample for the purpose of the question. GetAllAdrresses would return a new instance of another type so it would be thread safe.
My concern is that if many requests are made at the same time I'm not returning a person instance with the name of one request and surname of another.
It will only be thread-safe if GetAllAddresses is thread-safe. Otherwise, it's fine.
Regarding your UPDATE 1, yes, that will work fine. It will never get confused as you described. It's always creating new instances of objects, so there is no chance that the various threads will interfere with each other's data.
Given that GetAllAddresses only performs read actions, then the static method is entirely thread safe as each re-entering thread will create its own Person instance, the reference to which will be stored on the stack.
So, regarding UPDATE 1, because each thread is working with a new Person instance, there is no way that two different threads could write to the same person instance.
From what I understand, you try to make a new Person and return it to your page.
By that code the thread safe have no actually meaning. What you should look, is the moment you going to save that person back on the database, there you must make it thread safe to avoid to write it multiple times.
There are two ways to make it safe when you going to write it back on the database (create new, or make update)
One is to use mutex, and the second is to use the standard asp.net session that is lock the page, and its going to make thread safe the full process.

Categories