none
Invoking different operations one after another on single thread object RRS feed

  • Question

  • I have a situation where I want the same thread to perform multiple operations. refer to code below:


    namespace ConsoleApplication1
    {
    public interface ISample
    {
        void show();
    }
    class A : ISample
    {
        public void show()
        {
            Console.WriteLine("Inside A");

        }
    }

    class B : ISample
    {
        public void show()
        {
            Console.WriteLine("Inside B");

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ISample aObj = new A();
            System.Threading.ThreadStart ts1 = new System.Threading.ThreadStart(aObj.show);
            System.Threading.Thread t1 = new System.Threading.Thread(ts1);
            t1.Start();
            t1.Join();
            aObj = new B();
            t1.Start();
            Console.ReadLine();
        }
    }

     

    Above code results in exception. I have seen lot of discussion on restarting the thread. In my case I want to perform multiple operations one after another on same thread. for me, I am looking out for solution to run different methods from different objects on same thread. All these objects are of classes implementing same interface as done in above code. Please suggest me best way to perform this. In other words, if a method is complete then same thread should start the method of another object. Is this possible? Note that I do not know beforehands what methods the available thread have to execute.

    Wednesday, July 10, 2013 7:44 AM

Answers

  • "if a method is complete then same thread should start the method of another object"

    This really has nothing to do with threads, it's your job to simply write the necessary method calls somewhere. It's no different from writing code like the following:

    ISample aObj = new A();
    aObj.show();
    aObj = new B();
    aObj.show();

    "Note that I do not know beforehands what methods the available thread have to execute."

    Well, maybe you should figure out that part first because you can't write code if you do not know the details. Who decides what methods to execute and when?

    Wednesday, July 10, 2013 8:03 AM
    Moderator