【问题标题】:Csharp The calling thread cannot access this object because a different thread owns it [duplicate]Csharp调用线程无法访问该对象,因为不同的线程拥有它[重复]
【发布时间】:2012-06-11 02:43:03
【问题描述】:

可能重复:
Updating UI from a different thread
The calling thread cannot access this object because a different thread owns it

祝大家有美好的一天。 我的聊天应用程序有问题,我需要一直刷新我的聊天但错误提示。我不知道如何解决这个问题。我希望有一个人可以帮助我。 这是我的代码:

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";
        }
    }

【问题讨论】:

标签: c# wpf multithreading


【解决方案1】:

尝试 textBlockChatArea.Invoke("委托一个更新 Text 属性的方法")

1. 声明一个代表 公共代表无效UpdateChatAreaCallback(字符串文本); 2. 创建一个将更新文本框的方法: public void UpdateChatArea(string text){textBlockChatArea.Text += text;} 3.调用方法: textBlockChatArea.Invoke(new UpdateChatAreaCallback(UpdateChatArea, "new text"));

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 2014-02-13
    • 2012-06-03
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多