Winforms : avoid freeze application

后端 未结 1 1652
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 07:01

I do some operation on \"big\" file (around 4Mb)

I do this : 1. Get all files from a directory and place them in an IList MyInfoClass has properties : name, extensio

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 07:16

    The application freezes because you are performing the file parsing in the main thread. You could use BackgroundWorker to perform operation on a new thread. Here's some pseudo code that might help you to get started:

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

    0 讨论(0)
提交回复
热议问题