使用 .Net Compact/Windows CE 从线程中的数据设置标签文本



我似乎找不到有关如何执行此操作的可靠信息来源。我正在做的事情的细分。我有一个服务器/客户端正在运行,它在线程上运行。收到信息后,我需要将这些信息放入标签中。

为了完全清楚,消息已收到我想显示在标签中。

我的听力课上的代码:

public void receiveMessage(IAsyncResult ar)
{
//read from client
int bytesRead;
try
{
lock (_client.GetStream())
{
bytesRead = _client.GetStream().EndRead(ar);
//Console.WriteLine(ASCIIEncoding.ASCII.GetString(data, 0, bytesRead));
}
//if client has disconnected
if (bytesRead < 1)
return;
else
{
//get the message sent
string messageReceived =
ASCIIEncoding.ASCII.GetString(data, 0, bytesRead);   
if (frmMain.InvokeRequired)
{
frmMain.UpdateData(messageReceived);
}
}
//continue reading from client
lock (_client.GetStream())
{
_client.GetStream().BeginRead(
data, 0, _client.ReceiveBufferSize,
receiveMessage, null);
}
}
catch (Exception ex)
{
}
}

来自 frmMain.UpdateData 的代码:

public void UpdateData(string text)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(UpdateData), new object[] { text });
return;
}
stat_bar.Text = text;
}

这在普通的桌面 win 表单应用程序上工作正常。但是我需要在WindowsCE/中做一些工作。网络契约框架。

要从另一个非 GUI 线程更新 GUI 元素,您需要使用委托和调用。我总是使用这种模式:

delegate void SetTextCallback(string text);
public void addLog(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtLog.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(addLog);
this.Invoke(d, new object[] { text });
}
else
{
if (txtLog.Text.Length > 2000)
txtLog.Text = "";
txtLog.Text += text + "rn";
txtLog.SelectionLength = 0;
txtLog.SelectionStart = txtLog.Text.Length - 1;
txtLog.ScrollToCaret();
}
}

您可以使用所有类型的参数和元素来执行此操作。

最新更新