Skip to content

Threading

Uros Bregar

Asked Jun 14, 2008, 1:04 PM EDT2 answers
Share
LinkedInX

Hi

I have created a class that creates another thread. That background thread than creates a tcp client, connects to listener and waits for a message that will be send by the listener. When the message is received, it raises an event and waits for new messages. The problem is that the event is raised in background thread, instead in the thread that created that instance of my class. Does anybody has any idea how could I notify my main thread, so that thread could raise the event or if anybody has any other solution. I guess I need to implement something like Invoke method that every control has. but I don't know how I can do that. Any advice will be appreciated.

Thanks in advance

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    0
    I proposethree ways
    With Timer
    ex:
    //Notification method has to be overloded by a type object and void because of the delegate that will be used later called TimerCallback has this siganture
    void Notify(object Parameter)
    {
        //TO DO Perform the notification task
    }
    void Main()
    {
       //Define a timer and instanciate it
      Timer myTimer = new Timer(new TimerCallback(notify),null,3000/*wait for 3000*/,1000/*period*/);
    }
    Use this method if you want to be regulary notifyed

    Second method
    Use a delegate:
    //define a delegate
    delegate void MyDelegate();
    //now wiyhin the scoop of your method
    static MyDelegate MethodPointer;
    //Now in the scoop of your class you define a notification method 
    void Notify(IAsyncResult result)
    {
     //TO DO notification task
     int oResult = MethodPointer.EndInvoke(result) as int;
    }

    //Define the method to perform your main task
    public void/int/string/.. Method()
    {
       //TODO Perform the main task
    }
    //Within the Main now
    {
        Methodpointer = new MyDelegate(Method);
        //When you overload the method BeginInvoke the Asyncallback delegate will invoke Notify method at the end of thread traitement
        Methodpointer.BeginInvoke(...,New AsyncCallback(Notify),....);
    }
    Third method
    use the AutoResetEvent  object  within  the  threadpool context   
    0
  • 0

    Thanks for your help. I guess the second solution will be best for me

    Uros

    0