Visual Studio 2015 Debug doesn't work in multithread application

前端 未结 7 1751
被撕碎了的回忆
被撕碎了的回忆 2021-02-03 10:15

In my project I have a heavy part of code that should be executed on a separate thread without blocking UI. When debugger hits the breakpoint inside this code, VS2015 freezes fo

7条回答
  •  难免孤独
    2021-02-03 10:59

    I suggest that you use a combilation of a Timer and WaitHandle in your code instead of the for loop that causes high CPU usage. I made a simple change to your code to ease the CPU usage. Hope that help.

        public partial class Form1 : Form
        {
            EventWaitHandle _waitHandle ;
            System.Timers.Timer _timer; 
            public Form1()
            {
                InitializeComponent();
                _waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                _timer = new System.Timers.Timer();
                _timer.Interval = 100;
                _timer.Elapsed += OnTimerElapsed;
                _timer.AutoReset = true;
    
            }
    
            private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                _waitHandle.Set();
            }
    
            void FuncAsync(IProgress progress)
            {
                _timer.Start();
                int percent = 0;
                while (percent <= 100)
                {
                    if (_waitHandle.WaitOne())
                    {
                        progress.Report(percent);
                        percent++;
                    }
                }
                _timer.Stop();
    
            }
            void FuncBW(BackgroundWorker worker)
            {
                _timer.Start();
                int percent = 0;
                while (percent <= 100)
                {
                    if (_waitHandle.WaitOne())
                    {
                        worker.ReportProgress(percent);
                        percent++;
                    }
                }
                _timer.Stop();
            }
    
    
    
            void FuncThread()
            {
                _timer.Start();
                int percent = 0;
                while (percent <= 100)
                {
                    if (_waitHandle.WaitOne())
                    {
                        if (this.InvokeRequired)
                        {
                            this.Invoke((Action)delegate { label1.Text = percent.ToString(); });
                        }
                        else
                        {
                            label1.Text = percent.ToString();
                        }
                        percent++;
                    }
                }
                _timer.Stop();
            }
    
    
            ... your other code
        }
    

提交回复
热议问题