0

I'm trying to disable my button when it's clicked and after button code is complete, button should be enabled. Note that i'm using Thread.Sleep(500) once. I know how to disable the button, but I can't get button enabled properly. It enables before the text appears in textBox.

private void CPU_Click(object sender, EventArgs e)
    {
        //Disable button after click
        CPU.Enabled = false;

        //Put cursor in the end of MonitorLog 
        endPointer();

        MonitorLog.AppendText("********************************************\r\n");
        MonitorLog.AppendText("Starting System Monitor\r\n\n");

        //Check for CPU usage 
        var perfCpuCount = new PerformanceCounter
            ("Processor Information", 
            "% Processor Time", 
            "_Total");

        //Hide printing first CPU usage value which is always 0%
        perfCpuCount.NextValue();
        Thread.Sleep(500);
        //Changing CPU usage value to number with 2 decimal places and printing it out
        double cpuUsage = Math.Round(perfCpuCount.NextValue(), 2);

        MonitorLog.SelectionFont = new Font(MonitorLog.Font, FontStyle.Bold);
        MonitorLog.AppendText("CPU Usage:");
        MonitorLog.SelectionFont = new Font(MonitorLog.Font, FontStyle.Regular);
        MonitorLog.AppendText(string.Format(" {0}%\r\n\n", cpuUsage));

        //Scrolling to the end of the richTextBox
        scrollToEnd();

        CPU.Enabled = true;


    }
Tadas
  • 95
  • 10
  • Please add the code that you have written. By the way, explain what is this for. WinForms, WPF, ASP.NET? – Steve Dec 29 '15 at 23:25
  • @Steve, edited. I'm using WinForms. This code is for learning purposes so don't judge too hard. :P – Tadas Dec 29 '15 at 23:27
  • 2
    Well, who am I to judge you? However your code could not work as you expect because your code runs on the same thread that is responsible to update the ui. While your code runs there is no way to update your user interface. And Thread.Sleep stops the execution of the same thread so it is of no use here. You need to use an async/await pattern or a BackgroundWorker to run the code and update the ui – Steve Dec 29 '15 at 23:33
  • 4
    I think you could find this question helpful to solve your problem http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c?rq=1 – Steve Dec 29 '15 at 23:37

0 Answers0