为了学术目的,我把以前从windows表单到WPF的代码改编成WPF,问题是我不明白调用是如何工作的,希望有人在我阅读一些教程并解释我可以如何修改这些代码时,给我一些启发。
每当有人在send_click上发送消息时,它都会发送到一个服务器,该服务器向所有连接的套接字发送。我的问题是,如何调整这段代码,使文本块“可更新”?它说它已经被另一个线程(主线程)使用了。这是我的应用程序包含的代码。提前感谢!
更新1:这是我第一次尝试使用dispatcher调用http://gyazo.com/42008aacbec2f8494bb7c6c33889d9ad,但是我不理解这个walloftext背后的原因。
public Lobby()
{
InitializeComponent();
ctThread = new Thread(getMessage);
ctThread.Start();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();
}
TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
Thread ctThread;
private void btnSend_Click(object sender, RoutedEventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtInput.Text);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
Dispatcher.BeginInvoke(new Action(() =>
{
txtContent.Text = txtContent.Text + Environment.NewLine + " >> " + readData;
}));
}
} 发布于 2015-01-05 22:33:05
msg处于自己的线程中,因此必须将来自该函数的UI更新编组到UI线程上。您可以使用Dispatcher.BeginInvoke来完成以下操作:
Dispatcher.BeginInvoke(new Action(() =>
{
if (txtContent.Text != null)
{
txtContent.Text = txtContent.Text + Environment.NewLine + " >> " + readData;
}
});请注意,您应该考虑使用绑定而不是直接操作UI。
https://stackoverflow.com/questions/27788998
复制相似问题