c# - 紧凑框架: Update of label in thread not working

标签 c# multithreading compact-framework

在移动设备(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 部分(第三个代码片段)时,程序停止执行任何操作。没有崩溃,没有错误消息,没有异常。它就这样停止了。

这里出了什么问题?

顺便说一句,如果我离开 t.Join() ,线程根本不会启动......(为什么?)

最佳答案

我确信您会在这里遇到DeadLock

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

删除Join(),它应该可以工作。

Btw, if I leave the t.Join() away, the thread doesn't start at all... (Why that?)

不确定那是什么,这不是它应该的样子,尝试调试应用程序并找出答案。如果未找到,请向我们提供更多信息以获取帮助。

希望这有帮助

关于c# - 紧凑框架: Update of label in thread not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19220462/

相关文章:

c - 与 Pthread 共享有界缓冲区和互斥锁忙等待

compact-framework - 将 Bouncy CaSTLe 库与 .NET Compact Framework 一起使用

timer - 在 Compact Framework 中使用 System.Threading.Timer

c# - 如何将整数数组传递给方法 : Reflection C#

c# - .Net 邮件重复

c# - 将 float 转换为保留小数的字符串

c# - VSTO加载项CustomTaskPane升级到Word 2016/2019后将自行打开

c# - 数千个并发数据包,ThreadPool vs BeginRead?

javascript - Node.js单线程与并发

c# - 通过 C# 更改 Windows Mobile 5 主题