我有一个非常简单的 WinForms 应用程序,它使用从一些网络服务收集国家和地区并将收集的数据存储到文件中的类。这个 CollectData 类在控制台应用程序中完美运行,并通过 Console.WriteLine 通知每个步骤
我的代码如下所示:
public class CollectData
{
public string OutputFile { get; private set; }
public CollectData(string outputFile)
{
OutputFile = outputFile;
}
public void ProceedCollectingData()
{
Console.WriteLine("Getting countries...");
List<string> countries = GetWorldCountries();
foreach (string country in countries)
{
Console.WriteLine("Getting regions of country: " + country);
List<string> regions = GetCountryRegions(country);
AppendToFile(OutputFile, country, regions);
}
}
private List<string> GetWorldCountries()
{
List<string> list = new List<string>();
System.Threading.Thread.Sleep(20000); // here service fills list of countries.
return list;
}
private List<string> GetCountryRegions(string country)
{
List<string> list = new List<string>();
System.Threading.Thread.Sleep(20000); // here service fills list of regions.
return list;
}
private void AppendToFile(string outputFile, string country, List<string> regions)
{
// Save everything into output file.
}
}
和 WinForm 代码: private void btnCollectData_Click(object sender, EventArgs e) { CollectData collectData = new CollectData(tbOutputFile.Text.Trim()); collectData.ProceedCollectingData();
//???? what should be here
backgroundWorker.RunWorkerAsync(collectData);
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//???? what should be here?
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//???? what should be here?
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBarCountries.Value = 100;
progressBarRegions.Value = 100;
lblCurrentlyProgressingStatus.Text = "Done";
}
什么是错的,我应该在我的类中改变什么,我应该打开什么,从类方法返回或重新开发,开发和通知 progressBars 内部类逻辑的正确方法是什么?
我在互联网上搜索,所有示例都像 backgroundWorker_DoWork 中带有 Thread.Sleep 的简单“for”循环,但我有不同的情况。
感谢任何澄清回复!谢谢!