Thread交叉访问的问题.....

本来在做下载的进度条,自己的线程访问 ProgressBar时候出现错误:

错误代码

- -上网搜索下,原来我自己创建的线程和ui的线程不在一起.....看的我头大.

具体资料请看http://www.yoda.arachsys.com/csharp/threads/winforms.shtml

一直接调用委托不行的必须是,MethodInvoker updateCounterDelegate = new MethodInvoker(UpdateCount);

这个委托才可以,但是好象不能传递参数,可以通过,下面的方式传递参数,而且这样写就可以访问ui线程

 


       
int currentCount;

        
void UpdateCount()
        
{
            
int tmpCount;
            
lock (stateLock)
            
{
                tmpCount 
= currentCount;
            }

            counter.Text 
= tmpCount.ToString();
        }

 

二.- -另外自定义委托的调用

delegate void StringParameterDelegate(string value);

 

 

//-----用线程直接访这个方法就可以  
void UpdateStatus(string value)
        
{//--判断是否在ui线程中工作哦 
            if (InvokeRequired)
            
{

                
//--BeginInvoke 所调用的委托根本就是在 UI 线程中执行的。- -优点想递调用
                
// We're not in the UI thread, so we need to call BeginInvoke
                BeginInvoke(new StringParameterDelegate(UpdateStatus), new object[] { value });
                
return;
            }

            
// Must be on the UI thread if we've got this far,如果在直接设置
            statusIndicator.Text = value;
        }

 

 

例子

 

 

 

 

 

 

 

test_2.Designer.cs

 

test_2.cs

 

 

posted @ 2008-07-24 16:16  苹果王子  阅读(369)  评论(0编辑  收藏  举报