1

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

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

当我通过线程(仅作为示例)执行以下代码时,它会在大约 1 分钟内运行:

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

但是...如果我想更新用户,我必须使用委托从主线程更新 UI,下面的代码需要 - 永远 - 从字面上看,我不知道我还要等多久,我创建了这篇文章和它甚至没有完成 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(...)
        }
}
4

3 回答 3

5

不要在每个字节上更新 UI。仅每 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);
}
于 2010-05-11T21:36:04.467 回答
2

您过于频繁地更新 UI —— 100MB 文件中的每个字节都会导致 1 亿次 UI 更新(每个都编组到 UI 线程)。

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

于 2010-05-11T21:36:31.463 回答
1

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

    DateTime start = DateTime.Now;
    foreach (byte b in file.bytes)
    {
        if ((DateTime.Now - start).TotalMilliseconds >= 200)
        {
            UpdateCurrentFileStatus(current, total);
            start = DateTime.Now;
        }
    }
于 2010-05-12T00:25:24.790 回答