Freeing resources when thread is not alive

前端 未结 3 799
天命终不由人
天命终不由人 2021-01-24 10:54

I am using BackgroundWorker and inside it I am using foreach loop, inside which i create new thread, wait for it to finish, and than report progress and continue foreach loop. H

3条回答
  •  野性不改
    2021-01-24 11:05

    This might be cause garbage collection is not immediate. Try to collect after the thread goes out of scope:
    Edit:
    You also need to implement a better way to wait for the thread to finish other then busy wait(while (thread.IsAlive);) to save CPU time, you can use AutoResetEvent.

    private void DoWork(object sender, DoWorkEventArgs e) {
                var fileCounter = Convert.ToDecimal(fileNames.Count());
                decimal i = 0;
                var Event = new AutoResetEvent(false);
                foreach (var file in fileNames) {
                    i++;
                    var generator = new Generator(assembly);
    
                    {
                        var thread = new Thread(new ThreadStart(
                                delegate() {
                                    generator.Generate(file);
                                    Event.Set();
                                }));
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        //while (thread.IsAlive); // critical point
                        Event.WaitOne();
                    }
                    GC.Collect();
                    int progress = Convert.ToInt32(Math.Round(i / fileCounter * 100));
                    backgroundWorker.ReportProgress(progress);
                }
            }
    

提交回复
热议问题