日期:2014-05-19  浏览次数:20830 次

关于跨线程调用控件,谁来给我解释一下
我自己建了一个form,里面放了一个计时器,1秒钟触发一次,改变form里的textbox1控件的text属性,下面是代码:
    void   UpdateText(string   str)
                {
                        if   (this.textBox1.InvokeRequired)
                        {
                                SetCallBack   d   =   new   SetCallBack(UpdateText);
                                this.Invoke(d,   new   object[]   {   str   });
                                Debug.WriteLine( "if   执行 ");
                        }
                        else
                        {
                                this.textBox1.Text   =   str;
                                Debug.WriteLine( "else   执行 ");
                        }
                }

下面是Debug输出的结果:
“invokedTest.vshost.exe”(托管):   已加载“E:\mypro\invokedTest\invokedTest\bin\Debug\invokedTest.exe”,符号已加载。
“invokedTest.vshost.exe”(托管):   已加载“C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll”,已跳过符号加载。已对模块进行了优化并启用了调试器选项“仅我的代码”。
else   执行
if   执行
else   执行
if   执行
else   执行
if   执行
else   执行
if   执行
else   执行
if   执行
else   执行
if   执行
else   执行
if   执行
else   执行
if   执行
程序“[3448]   invokedTest.vshost.exe:   托管”已退出,返回值为   0   (0x0)。

谁能告诉我为什么会先执行else部分?明明是新线程要更改textbox1,应该是先执行if啊。

------解决方案--------------------
this.Invoke(d, new object[] { str });
Debug.WriteLine( "if 执行 ");

顺序换成

Debug.WriteLine( "if 执行 ");
this.Invoke(d, new object[] { str });

虽然你先进的if分支,但是在Invoke里递归调用了UpdateText,而输出是在Invoke之后执行的。