我正在使用C#和wpf构建基本的TCP客户端/服务器应用程序。 当客户端解析来自服务器的响应时,我试图通知用户控件(在我的情况下为按钮)。
据我了解,我必须在TcpClient类中创建一个事件,在解析响应时该事件将被触发,并且我必须将按钮订阅到该事件并使用Dispatcher.Invoke()。但是我对如何实现它一无所知,MSDN文档也没有帮助我。 我已经使用以下MSDN示例为服务器和客户端“ PoC”了它: https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example
在我的MainWindow上,有一个按钮“ test_btn”。当我解析来自服务器的响应时,我想将按钮的内容更新为“成功”。
我们将不胜感激
谢谢。
MainWindow.cs:
public MainWindow()
{
InitializeComponent();
Thread TcpThread = new Thread(new ThreadStart(AsynchronousClient.StartClient));
TcpThread.Start();
}
AsynchronousClient.cs:
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
if(response == "success)
{
// Update the button from the MainWindow
}
答案 0 :(得分:0)
我一个人来回答。
如果可以帮助某人:
我已经在MainWindow.cs中添加了
public delegate void updateNetworkButtonDelegate(string message);
public void updateNetworkButton(string message)
{
if (!test_btn.Dispatcher.CheckAccess())
{
test_btn.Dispatcher.Invoke(new updateNetworkButtonDelegate(updateNetworkButton), message);
}
else
{
test_btn.Content = message;
}
}
}
我已经修改了TcpClient以在参数中传递MainWindow:
public static void StartClient(MainWindow mw)
然后我可以使用:
更新按钮mw.updateNetworkButton(response);