使用后台线程时如何有效地显示文件的状态?
例如,假设我有一个 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(...)
}
}