2013-10-07 107 views
2

在一个移动设备(Windows Mobile)的程序中,我使用紧凑框架3.5, 我下载一个文件并希望通过在Windows中显示它来监视进度.Forms.Label。紧凑框架:更新线程中的标签不工作

这里我的代码:

我的线程开始(在一个按钮单击事件)

ThreadStart ts = new ThreadStart(() => DownloadFile(serverName, downloadedFileName, this.lblDownloadPercentage)); 
Thread t = new Thread(ts); 
t.Name = "download"; 
t.Start(); 
t.Join(); 

我的线程方法

static void DownloadFile(string serverName, string downloadedFileName, Label statusLabel) 
{ 
     HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(serverName); 
     do 
     { 
      //Download and save the file ... 
      SetPercentage(statusLabel, currentProgress); 
     } while(...) 
} 

的方法更新标签文本

private static void SetPercentage(Label targetLabel, string value) 
{ 
     if (targetLabel.InvokeRequired) 
     { 
      targetLabel.Invoke((MethodInvoker)delegate 
      { 
       targetLabel.Text = value; 
      }); 
     } 
     else 
     { 
      targetLabel.Text = value; 
     } 
} 

下载和保存部分工作正常,但是当谈到targetLabel.Invoke-part(第3代码片段)时,程序将停止执行任何操作。没有崩溃,没有错误信息,没有例外。它只是停止。

这里怎么回事?

顺便说一句,如果我离开了t.Join()的距离,该线程不启动在所有...(为什么呢?)

回答

2

敢肯定你会得到一个DeadLock这里。

主线程正在等待t.Join();然后当工作线程调用targetLabel.Invoke主线程无法调用它,因为它正在等待Join这是永远不会发生的。这种情况在计算机科学中被称为Deadlock

删除Join()它应该工作。

顺便说一句,如果我离开了t.Join()的距离,该线程不启动在所有...(为什么呢?)

不知道那是什么,是不是它应该是怎么样的,尝试调试应用程序并找出它。如果找不到,请提供更多信息以获得帮助。

希望这会有所帮助