?
Solved

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

Posted on 2009-12-19
13
Medium Priority
?
232 Views
Last Modified: 2012-05-08
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
0
Comment
Question by:KAMAU
  • 6
  • 6
13 Comments
 
LVL 3

Expert Comment

by:Birdbuster
ID: 26088111
Sounds like you need a static method.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26088414
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
 

Author Comment

by:KAMAU
ID: 26088500
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:KAMAU
ID: 26088502
Any code samples that would illustrate(psudo-code or actual real examples) would be much appreciated
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26089004
I'll try to post a simple example tonight or tomorrow morning...
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 1000 total points
ID: 26089373
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
 

Author Comment

by:KAMAU
ID: 26099247
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26099574
"...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
 

Author Comment

by:KAMAU
ID: 26099793
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26099912
"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
 

Author Comment

by:KAMAU
ID: 26101134
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26101596
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
 

Author Closing Comment

by:KAMAU
ID: 31668126
Thanks, this has put me on the right track, and thanks for sticking with clearing up my follow on questions. Regardsa
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Simple Linear Regression

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question