p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   C# 2005 (http://p2p.wrox.com/forumdisplay.php?f=138)
-   -   cross thread Error (http://p2p.wrox.com/showthread.php?t=60590)

angelboy July 27th, 2007 02:25 PM

cross thread Error
hi expert
i use the flowing code to read the file into textBox

my code is


public partial class Form1 : Form
        byte[] fileContent;
        AsyncCallback callBack;
        FileStream fs;
        public Form1()

        private void btnAsync_Click(object sender, EventArgs e)
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)

                fs = new FileStream(op.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true);
                callBack = new AsyncCallback(fs_ReadAsync);
                fileContent = new byte[fs.Length];
                fs.BeginRead(fileContent, 0, (int)fs.Length, callBack, null);



        private void fs_ReadAsync(IAsyncResult Result)

            if (Result.IsCompleted)

                txtResult.Text = Encoding.UTF8.GetString(fileContent);


but when i run the program and i press the brnAsync and choose my file i receive the flowing error


Cross-thread operation not valid:
 Control 'txtResult' accessed from a thread other than the thread it was created on.

help me

GeertVerhoeven July 28th, 2007 04:35 AM


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;

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


delegate void SetTextboxTextDelegate(string newText);

void SetTextboxText(string newText)
    if (this.InvokeRequired)
        this.Invoke(new SetTextboxTextDelegate(this.SetTextboxText), new
        object[] { newText });
        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)




All times are GMT -4. The time now is 01:54 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.