Skip to main content
 首页 » 编程设计

c#之通过 ref 值传递函数的进度是个好主意吗

2024年02月06日13oomusou

几天前我问了一个关于how to constantly check the progress of a function的问题但是我没有收到任何答复,所以我试图找到一种方法来做到这一点,所以我在我的函数中引用了参数,它们返回了我要处理的项目总数和当前处理的项目
< br/>

public void SaveInfoToDBFromFiles(string path,ref int TotalItems, ref int CurrentItem) 
{ 
  initialize the values; 
  do some stuff; 
 
  TotalItems=TotalNumberOfFiles; 
 
  foreach(file in path) 
  { 
   CurrentItem++; 
  }  
} 

在我的 UI winforms 中,我创建了一个线程,我有一个进度条,它显示了函数的当前进度,以及通过获取 CurrentItem 值更新进度条的计时器,

        System.Threading.Thread th = new System.Threading.Thread(() =>   SaveInfoToDBFromFiles(path,ref Total,ref  Current)); 
 
        th.Start(); 
        progressBar1.Value=Total; 
        timer1.Start(); 


    private void timer1_Tick(object sender, EventArgs e) 
    { 
        progressBar1.Value = Current; 
    } 

它工作得很好,但我想知道这是否是个好主意?

请您参考如下方法:

你可以用 - 我认为 - 现在更好的方式来做到这一点。

您可以使用 Progress<T>类并让框架将其编码回您的 UI 线程。

有点像这样:

var progress = new Progress<int>(currentItem => 
{ 
    progressBar1.Value = currentItem; 
}); 
 
await Task.Run(() => SaveInfoToDBFromFiles(path, progress); 

然后你就可以在save方法中报告进度了:

public void SaveInfoToDBFromFiles(string path, IProgress<int> progress) { 
    // .. other code here .. 
    var i = 0; 
 
    foreach (var file in path) { 
        progress.Report(i); 
        i++; 
    } 
} 

您甚至可以包装一个包含更多信息的自定义类型:

// first, a class to hold it all 
class MyType { 
    public string FileName { get; set; } 
    public int CurrentItem { get; set; } 
} 
 
// .. then you need to declare the Progress instance to hold your type 
 
var progress = new Progress<MyType>(myType =>  
{ 
    label1.Text = myType.FileName; 
    progressBar1.Value = myType.CurrentItem; 
}); 
 
// then when you're reporting progress you pass an instance of your type 
progress.Report(new MyType { 
    FileName = file, 
    CurrentItem = i 
});