Cross thread problem?

后端 未结 3 1015
后悔当初
后悔当初 2020-12-22 02:19

My error

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

相关标签:
3条回答
  • 2020-12-22 02:33

    You cannot directly access a control from another thread, you will have to invoke it.

    private delegate void ControlCallback(string s);
    
    public void CallControlMethod(string text)
    {
        if (control.InvokeRequired)
        {
            ControlCallback call = new ControlCallback((s) =>
            {
                // do control stuff
            });
            control.Invoke(call, new object[] { text });
        }
        else
        {
            // do control stuff
        }
    }
    
    0 讨论(0)
  • 2020-12-22 02:38

    you can't access the UI on a different thread than what it was created on. From inside your secondary thread (the one that runs your callback handler) you will need to call Form.BeginInvoke to register a method that will be run on the UI thread. From that method you can update your UI controls

    0 讨论(0)
  • 2020-12-22 02:55

    I think AddMesToMailList() is trying to modify the view elements but it is on a wrong thread.

    Try something like this

    void AddMesToMailList()
    {
        if (this.InvokeRequired)
        {
             this.BeginInvoke(new Action(AddMesToMailList));
             return;
        }
    
        // do stuff that original  AddMesToMailList() did.
    }
    

    EDIT: SaveMail is a little complicated as it has a return value but you can try this

    public int SaveMail(ImapX.Message mess)
    {
         if(this.InvokeRequired)
         {
                return (int) this.Invoke(
                       new Func<ImapX.Message, int>( m => SaveMail(mess)) );
         }
         else
         {
    
            if (!File.Exists(@"D:\" + Username + "\\" + MailTree.SelectedNode.Text + "\\" + mes.MessageUid.ToString() + ".eml"))
            {
                mess.Process();
                mess.SaveAsEmlToFile(@"D:\" + Username + "\\" + MailTree.SelectedNode.Text + "\\", mes.MessageUid.ToString());   //Store messages to a Location 
    
            }
           // mes.MessageUid=mess.MessageUid;
            return 1;  
    
         }
    
    
    
    }
    
    0 讨论(0)
提交回复
热议问题