获得跨线程操作异常

时间:2013-11-19 21:35:59

标签: c# exception

我正在尝试从类中更新richtextbox,而不是从表单中更新。这是我的代码:我将Form作为参数传递给Client类的构造函数。

 public partial class Form1 : Form
 {
     public void AppendText(string s)
     {
         richtextbox_server_activities.AppendText(s + "\n");
     }

     public Form1()
     {
         client = new Client(e.Accepted,e.user,this);
     }

   //rest of the code of the form
 }

和“Client”类中的函数,我尝试更新gui:

private Form1 form;

public Client(string username, Form1 form)
{
    this.form = form;
    _baseSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    this.username = username;
}

private void process()
{
    int id = pr.ReadInt32();
    long index = pr.ReadInt64();
    int size = pr.ReadInt32();
    byte[] buffer = pr.ReadBytes(size);

    TransferQueue queue = _transfers[id];

    queue.Write(buffer, index);

    queue.Progress = (int)((queue.Transferred * 100) / queue.Length);
    if (queue.LastProgress < queue.Progress)
    {
        queue.LastProgress = queue.Progress;

        if (ProgressChanged != null)
        {
             ProgressChanged(this, queue);
        }

        if (queue.Progress == 100)
        {   //HERE IS WHERE I GET EXCEPTION
            this.form.AppendText("Client " + this.username + " has completed uploading the file " + queue.Filename + ".");
            queue.Close();

             if (Complete != null)
             {
                 Complete(this, queue);
             }
         }
}

但是我收到一个错误,说明跨线程操作无效:控件'从其创建的线程以外的线程访问。我看了类似的问题,但我仍然得到这个错误。有谁能看到这个问题?

谢谢

1 个答案:

答案 0 :(得分:1)

问题是您正在使用Form1类中的另一个线程访问Client控件,您需要调用正确的线程。

示例:

public void AppendText(string s)
{
    Invoke((Action)delegate { richTextBox1.AppendText(s + "\n"); });
}

delegate传递到Client而不是整个表单

可能是更好的选择

示例:

 public Form1()
 {
     client = new Client(e.Accepted,e.user,AppendText);
 }



public class Client
{
    private Action<string> _callback;

    public Client(string username, Action<string> callback)
    {
        _callback = callback;
    }


    private void Process()
    {
        .......

        _callback("Client " + this.username + " has completed uploading the file " + queue.Filename + ".");
    }
}