I have a question. Is it possible and valid, if I have an object with a method DoSomething(), if I create multiple threads for this method, will it work and would it run as a seperate thread of its own?
E.g.
public class SomeClass
{
public void DoSomething()
{
//somethings done here
}
}
public class MainProgram
{
public MainProgram()
{
InitializeComponents();
}
protected override OnStart(string[] args)
{
SomeClass sc = new SomeClass();
Thread workerOne = new Thread(() => sc.DoSomething());
workerOne.Start();
Thread workerTwo = new Thread(() => sc.DoSomething());
workerTwo.Start(); //start a new thread calling same method
}
}
I hope that kind of explains what I mean. Would this work or cause any problems?
I am writing a program that needs to almost be realtime software, I am currently deciding whether initialising a new instance of SomeClass is better or not?
Hope someone can answer. If my question's dont make sense, please comment and I'll explain further!
Thanks,
Base33
PS The code was written specifically for the example :)
Each thread has a separate call stack, so yes they can both be using the same method on the same object. And indeed, if needed each thread can (via recursion) call the same method on the same instance multiple times if you really want.
However, what might trip you up is if you are using state in that object (instance or static fields, etc, and anything related from that state). You will need to ensure your access to any shared state gives full consideration (and presumably synchronisation) to multi-threaded access.
Yes you can do that. You will however have to make sure that your member accesses within that method are thread safe.
If you mutate the state of the object you should either lock your reads and writes (not speaking of any particular mechanism) or verify that it's harmless to interupt the method at any given time and that the other call on a different thread will still work correctly
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