0

Possible Duplicate:
Updating UI from a different thread
The calling thread cannot access this object because a different thread owns it

Good day to all. I have problem with my chat application, i need to refresh my chat all the time but the error is prompting. I dont know how to fix this issue. i hope someone can help me. here is my code:

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";
        }
    }
Community
  • 1
  • 1
Sephiroth111
  • 127
  • 1
  • 5
  • 14
  • 1
    Lots of things wrong with this code: new thread on each timer tick; not disposing connection; updating UI controls on a thread – Mitch Wheat Jun 11 '12 at 02:45
  • 1
    WPF? WinForms? This is a duplicate. [You need to manipulate on `textBlockChatArea.Text` on the correct thread](http://stackoverflow.com/search?q=calling+thread+cannot+access+this+object+because+a+different+thread+owns+it). – user7116 Jun 11 '12 at 02:46
  • pardon, im still beginner on using Thread class. im using wpf – Sephiroth111 Jun 11 '12 at 03:20

1 Answers1

1

try textBlockChatArea.Invoke("delegate to a method that update the Text property")

1. Declare a delegate   
    public delegate void UpdateChatAreaCallback(string text);
2. Create a method that will update the textbox:
    public void UpdateChatArea(string text){textBlockChatArea.Text += text;}
3. Invoke the method:
    textBlockChatArea.Invoke(new UpdateChatAreaCallback(UpdateChatArea, "new text"));
Pu Wang
  • 101
  • 1
  • 9