使用后台线程时高效显示文件状态 [英] Efficiently display file status when using background thread

查看:38
本文介绍了使用后台线程时高效显示文件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i efficiently display the status of a file when using a background thread?

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

For instance, lets say i have a 100MB file:

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

when i do the code below via a thread (just as an example) it runs in about 1 min:

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

但是...如果我想更新用户,我必须使用委托从主线程更新 UI,下面的代码需要 - 永远 - 实际上我不知道我还在等待多久,我创建了这篇文章甚至还没有完成 30%.

But... if i want to update the user i have to use a delegate to update the UI from the main thread, the code below takes - FOREVER - literally i don't know how long im still waiting, ive created this post and its not even 30% done.

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(...)
        }
}

推荐答案

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

I recommend that you update according to elapsed time so that you have predictable update intervals regardless of file size or system load:

    DateTime start = DateTime.Now;
    foreach (byte b in file.bytes)
    {
        if ((DateTime.Now - start).TotalMilliseconds >= 200)
        {
            UpdateCurrentFileStatus(current, total);
            start = DateTime.Now;
        }
    }

这篇关于使用后台线程时高效显示文件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆