简体   繁体   中英

Cross Thread Error on comboBox1 in winforms C#/NET

alredy a question out about this. but here comes another question little diffrent, and i cant find any awnsers to it!

String text = this.GuiThread(() => this.comboBox1.Text); 

 if (text == "this")
 {
   //do somthing spectacular!
 }

text is an empty variable or so..

Use of unassigned local variable. this is the ERROR i get..and iv tested all examples i can find here and at msdn.

im also having :

  public static class ControlExtensions
    {
        public static void GuiThread(this Control ctrl, Action action)
        {
            if (ctrl.InvokeRequired)
            {
                ctrl.BeginInvoke(action);
            }
            else
            {
                action.Invoke();
            }
        }
    }

ideas?

This code cannot compile. The GuiThread returns void, you are trying to assign that to a string. How you can get an exception is unguessable. It needs to at least look like this:

public static class ControlExtensions {
    public static T GuiThread<T>(this Control ctrl, Func<T> action) {
        if (ctrl.InvokeRequired) {
            return (T)ctrl.Invoke(action);
        }
        else {
            return action();
        }
    }
}

Don't write code like this, the actual ComboBox text you'll read is pretty random since it can be obtain while the user is modifying it. Give a thread the arguments it needs when you start it. The BackgroundWorker class keeps you out of trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM