c# - 使用 .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/.NetCompact 框架内做一些事情。
解决方案
要从另一个非 GUI 线程更新 GUI 元素,您需要使用 Delegate 和 Invoke。我总是使用这种模式:
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 + "\r\n";
txtLog.SelectionLength = 0;
txtLog.SelectionStart = txtLog.Text.Length - 1;
txtLog.ScrollToCaret();
}
}
您可以对所有类型的参数和元素执行此操作。
推荐阅读
- apache-spark - 为什么在基于具有 12 个不同值的列进行分区后得到更多分区
- angular - 为什么垫旋转器不显示?
- nlp - 快速加载预训练模型
- postgresql - 调用函数传递 JSONB 作为参数 - Postgres
- javascript - `@babel/preset-env` + `useBuiltIns` + `@babel/runtime` + `browserslistrc` 的最佳实践是什么
- c# - 获取 XAML 生成定义中的详细步骤
- sql - 选择所有字段满足条件的所有数据
- php - 验证 WooCommerce 结帐页面中的附加复选框字段
- powershell - 任务计划程序“CylancePROTECT”不执行 PowerShell 脚本
- qgis - 在QGIS字段计算器中计算两点之间的距离