0

I programming a c# code, I just used a thread to display a data on the UI, once per 100 ms. But I found the CPU(not the memory) is very high, from 20% to 70% immediately. Could someone else help me for this problem?

    public delegate void ThreadDisplayDelegate(string message);
    public ThreadDisplayDelegate _threaddelegate;
    public void DisplayCurrentDialog(string message)
    {
        if (_UI_receive.Dispatcher.CheckAccess())
        {
            _UI_receive.Text = message;
        }
        else
        {
            _UI_receive.Dispatcher.Invoke(_threaddelegate, message);
        }
    }
    public void ThreadUIDisplay()
    {
        _threaddelegate = new ThreadDisplayDelegate(DisplayCurrentDialog);
        while (_continue)
        {              
            DisplayCurrentDialog(_m_received_message);                
            System.Threading.Thread.Sleep(100);
        }
    }
Ben
  • 15
  • 4
  • Are you sure the problem is related to this piece of code? Your code is not related to serial communication. How is serial communication done? – Thomas Weller Jul 30 '15 at 21:32
  • 1
    See http://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful – 3dd Jul 30 '15 at 21:34
  • What does the UI do when it updates? – Thomas Weller Jul 30 '15 at 21:34
  • Yes, I am sure it is the problem of this piece of code. After I commented out this piece of code, this problem do not shown again. – Ben Jul 30 '15 at 21:36
  • it is used to show a real-time data (_m_received_message). – Ben Jul 30 '15 at 21:39
  • I don't think it is caused by Thread.Sleep(100). Because I used it in another thread, but it do not have the problem there. – Ben Jul 30 '15 at 21:46
  • I believe the Invoke is the one causing the issue. Can you not use BeginInvoke to make it asynchornous? – XtremeBytes Jul 30 '15 at 21:50
  • The `Sleep` has a bad smell for me. It's not that it is this call that is eating your CPU for lunch, but it blocks the calling thread for 100 ms every time `ThreadUIDisplay()` is called, and that seems undesirable. – 500 - Internal Server Error Jul 30 '15 at 21:56
  • So if you comment out the `while (_continue)` block of code, does the issue go away? Also, using `Task.Delay` instead of `Sleep` will not block the thread. – Jacob Roberts Jul 30 '15 at 21:56
  • I use BeginInvoke instead. It is perfect, thank you all guys. I have solved this problem. Task.Delay seems not work for this problem. – Ben Jul 30 '15 at 22:24

0 Answers0