CALLING A METHOD ON AN OBECT THAT EXISTS ON A SEPERATE THREAD

Hello,
I've got a bit of a stumbler. I've got a simple console application, the main thread creates 2 sub threads(Thread 1 and Thread 2), Thread 1 creates 3 objects, Object A,B and C. Thread 2 creates 3 objects as well Object X, Y and Z. Now i would like from the main thread call a method on Object C which exits on Thread 1 and then later from the Main thread call a method on Object Y which exists on Thread 2. Object A is a Car, object, and the method i'd like to call is ChangeCarColor(colour as string), Object Y is a person object and the method i'd like to call is SetPersonWeight(weight as integer). I've attached a simple diagram to illustrate what i'm trying to do
QUESTION.png
KAMAUAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Here's a bare bones example of a class that encapsulates a thread and passes out the dynamically created object via a custom event:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            mc.ObjectCreated += new MyClass.ObjectCreatedDelegate(mc_ObjectCreated);
            mc.Start();
        }

        static void mc_ObjectCreated(object a)
        {
            // ...do something with "a"...
        }
    }

    public class MyClass
    {

        public delegate void ObjectCreatedDelegate(Object a);
        public event ObjectCreatedDelegate ObjectCreated;

        private System.Threading.Thread T = null;

        public void Start()
        {
            if (T == null)
            {
                T = new System.Threading.Thread(Worker);
                T.Start();
            }
        }

        private void Worker()
        {
            System.Threading.Thread.Sleep(5000); // wait five seconds
            Object a = new Object();
            ObjectCreated(a);
        }

    }

}

Open in new window

0
 
BirdbusterCommented:
Sounds like you need a static method.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Encapsulate your Thread1 and Thread2 in their own custom CLASS.  Then you can either make the desired object a public property or make the class raise a CUSTOM EVENT that the main thread subscribes to.  The event will simply pass out a reference to the necessary object.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
KAMAUAuthor Commented:
Thnx Idle_Mind. I'm a little new to .NET programming. I'll need a bit more help to understand this. How do you encapsulate a thread into a custom class, considering a thread is a system class (right?), then how would i 'embed' the Objects into this custom thread?
Please expound on static method and how it would be useful in this scenario. Thanks
0
 
KAMAUAuthor Commented:
Any code samples that would illustrate(psudo-code or actual real examples) would be much appreciated
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
I'll try to post a simple example tonight or tomorrow morning...
0
 
KAMAUAuthor Commented:
Hi, i'm trying to implement and understand the code. Now lets assume that the class i want to create is a CAR.

MyClass mc = new MyClass();
            mc.ObjectCreated += new MyClass.ObjectCreatedDelegate(mc_ObjectCreated);
            mc.Start();

I've replaced as follows

The mc_ObjectCreated bit only gets fired when the object is created.
  static void mc_ObjectCreated(object a)
        {
            // ...do something with "a"...
How do i do something with a, how can i tell that a is of type Car?
        }

At the point of creating the object the mc_ObjectCreated code takes an Object as a parameter,how can this function tell that object A is of type Car?

Also once the object has been created. I want to write a simple function that changes the age of the car, that has been created to say 87.

MyCar mc = new MyCar();
            mc.ObjectCreated += new MyCar.ObjectCreatedDelegate(mc_ObjectCreated);
            mc.Start();


public class MyCar
    {

        public delegate void ObjectCreatedDelegate(Object a);
        public event ObjectCreatedDelegate ObjectCreated;

        private System.Threading.Thread T = null;

        public void Start()
        {
            if (T == null)
            {
                T = new System.Threading.Thread(Worker);
                T.Start();
            }

   private void Worker()
        {
            System.Threading.Thread.Sleep(5000); // wait five seconds
            Object a = new Object();
            ObjectCreated(a);
        }

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
"...how can this function tell that object A is of type Car?"

You can use the "is" keyword like this:

            if (a is Car)
            {
                Car car = (Car)a;
                car.Age = 87;
            }
0
 
KAMAUAuthor Commented:
I see, will try it out shortly, one more thing i curious, when the start method is executed, it triggers the Worker section of the code which creates the actually creates the object. This effectively creates the Car object on a separate thread. Correct? I just want to be sure i'm understanding it right.
Once the object has been created on the separate thread, the thread itself dies correct?
What i think i was try to illustrate from the diagram was Main thread--->creates Thread 1---->Thread 1 creates Obect CAR, now the Car object exists on Thread 1, when i type changeAge in the console window(MAIN Thread), it's routed to the appropriate thread..i.e executes the ChangeAge method on the Car object which exists in thread 1. Thread 1 never dies. I'm basically trying to have a way to offload any processing of objects to the thread that created the object, so the main method is never responsible for the objects created on sub Threads. As an add on if Thread1 and Thread 2 both had a Car Object, how would i be able to change the age of the Car object on thread 1 and but not on thread 2

Regards
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
"This effectively creates the Car object on a separate thread. Correct?"

Correct.

"the thread itself dies correct?"

Correct.  The thread "dies" when the last line in it is executed.  To keep it "alive" put everything inside a "while (true)" loop so it never reaches the end.  If you need to be able to gracefully exit the app then use a flag at the class level that the thread checks.

"As an add on if Thread1 and Thread 2 both had a Car Object, how would i be able to change the age of the Car object on thread 1 and but not on thread 2"

You could certainly create more than one instance of MyCar...but it would be up to you to keep track of which one was which.  You could either add them to a List() and use the Index position to identify them...or possibly add an "ID" member to MyCar.
0
 
KAMAUAuthor Commented:
Trying to keep the sub thread alive is proving a little challenging I've added a public boolean called terminate to the myClass bit

 public class MyClass
    {
public boolean terminate = false;

        public delegate void ObjectCreatedDelegate(Object a);
        public event ObjectCreatedDelegate ObjectCreated;

        private System.Threading.Thread T = null;

        public void Start()
        {
            if (T == null)
            {
                T = new System.Threading.Thread(Worker);
                T.Start();
while not terminate
     system.windows.forms.application.doevents
     thread.sleep(100)
End While
            }
        }


But when i run it, the code is permanently in the loop and never gives control back to the main thread. Will keep trying in the morning

Regards
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
It's Worker() that should have the while loop:   (since it's the one running in the other thread)

        private void Worker()
        {
            while (!terminate)
            {

                // do stuff in here            

            }
        }
0
 
KAMAUAuthor Commented:
Thanks, this has put me on the right track, and thanks for sticking with clearing up my follow on questions. Regardsa
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.