c# - 无法更改 TextBox 文本
问题描述
我想在我的 Backgroundworker 中更改 TextBox 的文本,但它不起作用,我在代码中找不到错误。
背景工作者:
class Check_Server
{
WebSocket webSocket = new WebSocket("ws://localhost:8548");
private Form1 Form1;
public void Check_WebSocket(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (!worker.CancellationPending)
{
Console.WriteLine("checking connection");
if (webSocket.IsAlive == true)
{
Console.WriteLine("connected");
}
else
{
Console.WriteLine("not connected");
Form1 form = new Form1();
form.SetText("XYZ");
MakeNewConnection();
}
}
}
void MakeNewConnection()
{
webSocket.Connect();
Thread.Sleep(10000);
}
}
形式:
public void SetText(string text)
{
if (InvokeRequired)
{
this.Invoke((MethodInvoker)delegate () { SetText(text); });
return;
}
textBox1.Text += text;
}
解决方案
你不显示你的表格。添加form.Show()
或form.ShowDialog()
,具体取决于您是否要等到用户关闭表单。
此外,我发现此扩展方法对于对控件进行线程安全更改非常有用。像这样使用它:textBox1.InvokeSave(() => textBox1.Text += text);
.
public static partial class ControlExtensions
{
public static void InvokeSave(this Control control, Action action)
{
Delegate del = action;
try
{
if (control.InvokeRequired)
{
control.Invoke(del);
}
else action();
}
catch (ObjectDisposedException)
{
// guess do nothing is fine then
}
}
}
推荐阅读
- spring-data-jpa - Spring JPA findByColumnNameLike 不起作用
- c# - 选择不等待 ASP.NET Core WebAPI 控制器中的异步函数
- java - Java:实现树及其节点的并行层次结构
- google-cloud-firestore - 每个数据库的移动设备 Cloud Firestore 并发连接限制和每个数据库每秒的最大写入次数
- javascript - 使用 JavaScript 映射嵌套数组
- java - 无法检测添加的自定义 jar 中的包
- c# - 如何在运行时从 dll 中引用静态类
- django - 为什么我不能在更新代码后使用 uwsgi 启动 django 项目
- python - 用于类组织的 Python 代码结构
- arrays - 在 MATLAB 中编写线性插值函数