Alex Rivera | Logout

Creating multiple threads for same method on an instance on an object

Asked 2012-06-11T19:41:36.460
11

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 :)

Edit
Report

1 Answer

3

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

answered 2012-06-11T19:45:56.450

Your Answer