代码之家  ›  专栏  ›  技术社区  ›  schmoopy

使用后台线程时有效显示文件状态

  •  1
  • schmoopy  · 技术社区  · 16 年前

    在使用后台线程时,如何有效地显示文件的状态?

    例如,假设我有一个100MB文件:

    当我通过一个线程(例如)执行下面的代码时,它将在大约1分钟内运行:

    foreach(byte b in file.bytes)
    {
       WriteByte(b, xxx);
    }
    

    但是…如果我想更新用户,我必须使用委托从主线程更新用户界面,下面的代码需要-永远-字面上我不知道我还等了多长时间,我创建了这篇文章,甚至还没有完成30%。

    int total = file.length;
    int current = 0;
    foreach(byte b in file.bytes)
    {
       current++;
       UpdateCurrentFileStatus(current, total);
       WriteByte(b, xxx);
    }
    
    public delegate void UpdateCurrentFileStatus(int cur, int total);
    public void UpdateCurrentFileStatus(int cur, int total)
    {
            // Check if invoke required, if so create instance of delegate
            // the update the UI
    
            if(this.InvokeRequired)
            {
    
            }
            else
            {
              UpdateUI(...)
            }
    }
    
    3 回复  |  直到 16 年前
        1
  •  1
  •   Ed Power    16 年前

    我建议您根据已用时间进行更新,以便无论文件大小或系统负载如何,都有可预测的更新间隔:

        DateTime start = DateTime.Now;
        foreach (byte b in file.bytes)
        {
            if ((DateTime.Now - start).TotalMilliseconds >= 200)
            {
                UpdateCurrentFileStatus(current, total);
                start = DateTime.Now;
            }
        }
    
        2
  •  5
  •   Byron Whitlock    16 年前

    不要在每个字节上更新用户界面。仅每100K左右更新一次。

    观察:

    int total = file.length;
    int current = 0;
    foreach(byte b in file.bytes)
    {
       current++;
       if (current % 100000 == 0)
       {
            UpdateCurrentFileStatus(current, total);
       }
       WriteByte(b, xxx);
    }
    
        3
  •  2
  •   Ragoczy    16 年前

    您过于频繁地更新UI——100MB文件中的每个字节都将导致1亿个UI更新(每个更新都被封送到UI线程)。

    将更新分成文件总大小的百分比,可能是10%甚至5%的增量。因此,如果文件大小为100字节,请在10、20、30等处更新UI。