I need to launch multiple threads, but each thread would have its own list. This means, the lists are not to be shared, but they will be accessed by different methods.
class foo()
{
//put the list definition here as a property?
public main()
{
launchthread(threadMethod1)
}
public void threadMethod1()
{
// create a list instance here?
// do something about the list, modify data in it
threadMethod2();
}
public void threadMethod2()
{
// do something about list, modify data in it
}
}
How should I properly define the list, where to put the definition? and is it has anything to do with thread-safe if I only want to have a thread private list?
I am looking for options other than passing the list as parameter for threadmethod2.
Assuming that I don't need to use ConcurrentBag/SynchronizedCollection or worry about the lock stuff?
Am I right that you are goind to start your threads something like this:
If so, then it completely thread-safe for you, and you no need in
ConcurrentCollection-class in yourfoodefinition, as there is only one thread which will access this variable. You don't need to add the list as a parameter as eitherthreadMethod1orthreadMethod2are supposed to be instance-methods, and the code inside them will see the same reference of theTLSvariable.I want to point out that you aren't using default coding standarts for the C# - the class names and method names aren't in CamelCasing, for example. I think that your code needs to be formatted properly.
Also I want to note that the
threadMethod1orthreadMethod2shouldn't bepublicas they are called from inside the class only, and you should restrict other classes from using them (if I understood your architecture well).Good reference about
TLS(thread-local-storage) from comments.