0

This is a method in the other class that i want to get the message from in my mainform.

 string message = Encoding.ASCII.GetString(data);
 Console.WriteLine(message);

Can i subscribe to this method from the main method somehow to get the data each time this method is triggered?

Edit: Okay so this is what my code looks like now:

                    } else {
                    string message = Encoding.ASCII.GetString(data);
                    DoSomething(message);
                    //Console.WriteLine(message);
                }
            } catch (Exception ex) {
                Log("Error recieving data: " + ex.ToString());
            }
        }
    }

    public delegate void SomethingHappenedHandler(string s);
    public SomethingHappenedHandler SomethingHappened = null;

    public void DoSomething(string message)
    {
        Console.WriteLine(message);
        var sh = SomethingHappened;
        if (sh == null)
        {
            sh(message);
        }
    }

And in the main method:

            dht.dhtNode.SomethingHappened += (msg) =>
        {
            talkText.Text += "[Friend]:  " + msg + "\n\n";
        };

But it does not trigger it? what else should i do to make it work?

  • 4
    I'm not clear on what you're trying to do. What's this other method? Why can't you just call it? What went wrong when you tried to call it? – John Saunders Aug 16 '13 at 19:27
  • the method is running in another thread and is triggered when i get an udp packet so i cant call it as it is. – user2676748 Aug 16 '13 at 19:31
  • 1
    Methods are not "in threads". What did you try to do to call it, and what was the problem when you did? – John Saunders Aug 16 '13 at 19:32
  • Now the context has changed. It is now a followup question because `Okay so this is what my code looks like now` is my answer's copy (which also explains your *new* problem) – I4V Aug 16 '13 at 22:15
  • 1
    Try `if (sh != null)` – John Saunders Aug 16 '13 at 23:05

1 Answers1

0

You can create a delegate and subscribe to it. For ex,

someInstance.SomethingHappened += (msg) =>
    {
        //your code
    };

public delegate void SomethingHappenedHandler(string s);
public SomethingHappenedHandler SomethingHappened = null;

public void DoSomething()
{
    string message = Encoding.ASCII.GetString(data);
    Console.WriteLine(message);

    var sh = SomethingHappened;
    if (sh != null) sh(message);
}

EDIT: And to display the result in a UI control you should be aware of Cross-threads operations. Cross-thread operation not valid

Community
  • 1
  • 1
I4V
  • 34,891
  • 6
  • 67
  • 79