Csharp 调用线程无法访问此对象,因为其他线程拥有它
本文关键字:线程 因为 其他 拥有 对象 调用 访问 Csharp | 更新日期: 2023-09-27 18:36:49
可能的重复项:
从其他线程
更新 UI 调用线程无法访问此对象,因为其他线程拥有它
祝大家美好的一天。我的聊天应用程序有问题,我需要一直刷新我的聊天,但错误提示。我不知道如何解决这个问题。我希望有人能帮助我。这是我的代码:
void timerChatRefresh_Tick(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(ChatRefresh));
thread.Start();
}
private void ChatRefresh()
{
conn = new MySqlConnection("Server=...; Database=...; Uid=...; Password=...;");
ds.Clear();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "select * from chatmessagetbl";
da.SelectCommand.CommandType = CommandType.Text;
da.Fill(ds, "chatmessagetbl");
foreach (DataRow item in ds.Tables["chatmessagetbl"].Rows)
{
textBlockChatArea.Text += item["username"].ToString() + ": " + item["message"].ToString() + "'n";
}
}
try textBlockChatArea.Invoke("delegate to a method for new the Text)
1. 声明委托 公共委托无效 更新聊天区回调(字符串文本);2. 创建一个将更新文本框的方法: public void UpdateChatArea(string text){textBlockChatArea.Text += text;}3. 调用方法: textBlockChatArea.Invoke(new UpdateChatAreaCallback(UpdateChatArea, "new text"));