Search code examples
c#formstimerdelaythread-sleep

C# "Thread.Sleep" Messing My Program (Form Doesn't Show Up)


i add a loop to my program just to check something...(For verification)

for (int i = 1; i < total; i++){
   for (int row = 0; row < 4; row++){
      for (int col = 0; col < 4; col++){ 
           pixel = block[i][row][col];
           label1.Text = pixel.R.ToString("X");
           System.Threading.Thread.Sleep(100);}}}

After Add this loop program works , but form doesnt show up. I Start Debuging and i saw that in this line it stops. Dont go any further.

Application.Run(new Form1());

Basicly begining of the program. So I isolate the System.Threading.Thread.Sleep(100);}}} Part it is working now. Why this code is causing problem. I used the using System.Threading.Tasks;. Any idea or i can use other delay function... İ waiting for your help. Thank you..


Solution

  • You should never, ever, block the UI Thread (by means of sleeping or doing some heavy work) as the Thread can only either handle UI-Events (clicks, rerendering, resizing) or run your code, not both. In cases where you must execute some long running code from a event-handler, you can either start a new thread to do the work or run async code.

    For you, something like this should work just fine:

    public async void Form1_Load(object sender, EventArgs e) {
        for (int i = 1; i < total; i++){
           for (int row = 0; row < 4; row++){
              for (int col = 0; col < 4; col++){ 
                   pixel = block[i][row][col];
                   label1.Text = pixel.R.ToString("X");
                   await Task.Delay();
              }
           }
        }
    }
    

    While Sleep blocks the thread while it waits, await Task.Delay(); does not. It actually returns and lets the thread continue doing whatever it was doing previously and notifies the thread when it finished waiting so the thread can come back to your function later and continue running your code. (This is a simplification of how async and await works in C#)