我对“大”文件(大约4Mb)进行了一些操作

我这样做:
1.从目录中获取所有文件,并将它们放在IList中。MyInfoClass具有以下属性:name,extension,fullPath,creationDate,contentPart
2.我执行Linq查询以仅获取某些扩展名类型。
3.我循环搜索Linq查询结果,并针对每个结果打开文件,执行一些操作(获取值),然后将结果放入MyFileIno.ContentPart中。

仅供参考:30个文件,这是一个14秒的操作

辛苦了

问题是,当我从UI运行我的库时,当我单击按钮时,窗口在操作期间冻结。我想要 :


不冻结表格的解决方案
查看进度操作


您能给我最佳实践来解决这种问题吗?

谢谢,



public class FileManager
{
    public string CurrentFileName { get; set; }
    public void Validation(string path)
    {
        IList<InfoFile> listFile = GetListFile(path);
        foreach (InfoFile item in listFile)
        {
            CurrentFileName = item.Name;
            .....
        }
    }
}


private void button1_Click(object sender, EventArgs e)
{
    var worker = new BackgroundWorker();
    worker.DoWork += (s, args) =>
    {
        int percentProgress = 6;
        FileManager fileManager = new FileManager();
        fileManager.Validation(@"C:.....");
        ((BackgroundWorker)s).ReportProgress(percentProgress, fileManager.CurrentFileName);
    };

    worker.ProgressChanged += (s, args) =>
    {
        var currentFilename = (string)args.UserState;
        label1.Text = currentFilename;
        progressBar1.Value = args.ProgressPercentage;
    };

    worker.RunWorkerCompleted += (s, args) =>
    {
        progressBar1.Value = 0;
    };
    worker.RunWorkerAsync();
}

最佳答案

该应用程序冻结,因为您正在主线程中执行文件解析。您可以使用BackgroundWorker在新线程上执行操作。以下是一些伪代码,可以帮助您入门:

private void button1_Click(object sender, EventArgs e)
{
    var worker = new BackgroundWorker();
    worker.DoWork += (s, args) =>
    {
        // Here you perform the operation and report progress:
        int percentProgress = ...
        string currentFilename = ...
        ((BackgroundWorker)s).ReportProgress(percentProgress, currentFilename);
        // Remark: Don't modify the GUI here because this runs on a different thread
    };
    worker.ProgressChanged += (s, args) =>
    {
        var currentFilename = (string)args.UserState;
        // TODO: show the current filename somewhere on the UI and update progress
        progressBar1.Value = args.ProgressPercentage;
    };
    worker.RunWorkerCompleted += (s, args) =>
    {
        // Remark: This runs when the DoWork method completes or throws an exception
        // If args.Error != null report to user that something went wrong
        progressBar1.Value = 0;
    };
    worker.RunWorkerAsync();
}

10-07 19:03
查看更多