Creating multiple threads for the same method in an instance of an object

I have a question. Is this possible and valid if I have an object with the DoSomething () method, if I create several threads for this method, will it work and will it work as a separate thread?

eg.

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 this explains what I mean. Will this work or cause any problems?

I am writing a program that should be almost real-time, currently I am deciding whether it is better to initialize a new instance of SomeClass or not?

Hope someone can answer. If my question does not make sense, please comment and I will explain further!

Thanks,

Base33

PS The code was written specifically for example :)

+6
source share
4 answers

Each thread has a separate call stack, so yes, they both can use the same method on the same object. And indeed, if necessary, each thread can (through recursion) call the same method in the same instance several times if you really want to.

However, what can amaze you if you use a state in this object (instances or static fields, etc., and everything related to this state). You need to ensure that your access to any shared state fully takes into account (and presumably synchronization) multi-threaded access.

+12
source

Yes you can do it. However, you need to make sure that accessing your members in this method is a safe thread.

If you mutate the state of an object, you must either block your reads and writes (not to mention any particular mechanism), or make sure that it is safe to interupt the method at any time and that another call in another thread will still working correctly

+3
source

Is it possible and really, if I have an object with the DoSomething () method, if I create several threads for this method, will it work and will it work as a separate thread?

Yes it is possible. In the sample code, DoSomething is called on the same instance of SomeClass . Both threads share this. You have two different threads, but one common object.

Will this work or cause any problems?

It completely depends on your use case. It may or may not be. If the objects are separated, you need to synchronize access with them.

+1
source

He has no problem. I will work without errors.

This is similar to creating an object and a call method on this object twice. only fact is that two cases of calling the same method are on a different thread.

+1
source

Source: https://habr.com/ru/post/917823/


All Articles