View Single Post
  #2 (permalink)  
Old July 28th, 2007, 04:35 AM
GeertVerhoeven GeertVerhoeven is offline
Authorized User
 
Join Date: Sep 2004
Location: Edegem, Antwerpen, Belgium.
Posts: 40
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi,

This is because you are trying to update the value of textbox which is hosted in a different thread. It is not possible to change the value of a control from a different thread.

To update the control from a different thread you need to use the invoke method. With this method you can call a method on the main thread that allows to update the control.

Here is a sample:

private void fs_ReadAsync(IAsyncResult Result)
{
    FileStream fs = (FileStream)result.AsyncState;
    fs.EndRead(result);
    fs.Close();

    string text = Encoding.UTF8.GetString(buffer);

    SetTextboxText(text);
}

delegate void SetTextboxTextDelegate(string newText);

void SetTextboxText(string newText)
{
    if (this.InvokeRequired)
        this.Invoke(new SetTextboxTextDelegate(this.SetTextboxText), new
        object[] { newText });
    else
        txtResult.Text = newText;
}

The InvokeRequired checks whether the control is accessible from the current thread. If not, you need to call the Invoke method and pass an instance of a delegate. The Invoke method then executes the method in the delegate on the same thread as the control's thread.

Another possibility is to use the BackGroundWorker (see http://geertverhoeven.blogspot.com/2...undworker.html)

Greetz,

Geert



http://geertverhoeven.blogspot.com