Jeroen Kolk

Jeroen Kolk

  • NA
  • 11
  • 719

Threads.join() doesn't work like expected

Nov 5 2017 8:00 AM
Hi, I am totally new to C# and doing a retraining.
 
Today I walked into a little problem I can't solve yet.. 
 
I did a tutorial from Pragmtech on youtube: 
 https://www.youtube.com/watch?v=SgHYVPKJRX8&list=PLAC325451207E3105&index=102
 
 
The problem is that  when running the code it doesn't show the text "processing file. Please wait".  
 
I hope someone can help me out. Thx!
 
  1. private int CountCharacters()  
  2.         {  
  3.             int count = 0;  
  4.             using (StreamReader reader = new StreamReader(@"C:\Users\TTTG11133.NOA\Documents\JeroenK\Test\AsyncAwaitPragmTech101\data.txt"))  
  5.             {  
  6.                 string content = reader.ReadToEnd();  
  7.                 count = content.Length;  
  8.                 Thread.Sleep(5000);                  
  9.             }  
  10.             return count;  
  11.   
  12.         }  
  13.   
  14.   
  15.         //Async await with blocking (using task)  
  16.         private async void btnProcess1_Click(object sender, RoutedEventArgs e)  
  17.         {  
  18.   
  19.    
  20.             Task<int> task = new Task<int>(CountCharacters);  
  21.             task.Start();  
  22.   
  23.             lblCount.Text = "processing file. Please wait...";  
  24.             int count = await task;  
  25.    
  26.             lblCount.Text = count.ToString() + "characters in file";  
  27.             myTextBox.Text = "jeroen";  
  28.   
  29.         }  
  30.   
  31. private void btnProces2_Click(object sender, RoutedEventArgs e)  
  32.         {  
  33.               
  34.             int count = 0;  
  35.   
  36.             Thread thread = new Thread(() => { count = CountCharacters(); });  
  37.             thread.Start();  
  38.               
  39.             myTextBlock2.Text = "processing file. Please wait...";  
  40.             thread.Join(); // The next string should appear after  5 sec.  
  41.             myTextBlock2.Text = count.ToString();  
  42.   
  43.   
  44.   
  45.               
  46.         }  

Answers (3)