这是我希望从我的主窗体中获取消息的另一个类中的方法。
string message = Encoding.ASCII.GetString(data);
Console.WriteLine(message);
我可以以某种方式从main方法订阅此方法,以便每次触发此方法时获取数据吗?
编辑: 好的,这就是我现在的代码:
} 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);
}
}
在主要方法中:
dht.dhtNode.SomethingHappened += (msg) =>
{
talkText.Text += "[Friend]: " + msg + "\n\n";
};
但是它没有触发它?我还应该做些什么让它发挥作用?
答案 0 :(得分:0)
您可以创建委托并订阅它。例如,
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);
}
修改强> 要在UI控件中显示结果,您应该了解跨线程操作。 Cross-thread operation not valid