PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
Simple exercise not working?-VBForums
Results 1 to 10 of 10

Thread: Simple exercise not working?

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    4,942

    Simple exercise not working?

    I'm pretty inexperienced with C# but I'm trying to get it figured out. I have a very simple UI that I can't get working and again...it's just lack of knowledge as to how C# works. Below is my code and it's pretty self explanatory. You click on the Button control and and it should display "Iteration ?" 50 times. The problem is that nothing is printing in the textbox.

    Code:
    using System;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public TimeSpan interval;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                interval = new TimeSpan(0, 0, 1);
                PrintIt();
            }
            //
            //
            //
            private void PrintIt()
            {
                text1.Text = "";
                label1.Visible = true;
    
                for (int x = 0; x < 50; x++)
                {
                    text1.Text += "Iteration " + (x + 1) + "\r\n";
                    Thread.Sleep(interval);
                }
            }
        }
    }
    Last edited by blakemckenna; May 21st, 2020 at 05:22 PM.
    Blake

  2. #2
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    5,907

    Re: Simple exercise not working?

    Dumb question #1: You did set the textbox Multiline property to True?

    Dumb question #2: You did wait 50 seconds to see if the strings would show up in the textbox?

    Dumb observation #1: Just as in VB.Net, if you are going to have a long (in time 50 seconds) loop in the GUI, the GUI can't update until you leave the Sub. If you want to see the values in the Textbox as you write them, then refresh the textbox.
    Code:
            text1.Text += "Iteration " + (x + 1) + "\r\n";
            text1.Refresh();
            Thread.Sleep(interval);
    Dumb observation #2: You shouldn't have a loop that takes a long time in GUI code. You don't want the GUI to be unresponsive for 50 seconds. Use a timer to give you ticks at one second intervals and update the textbox from there. The code should be event driven, not a loop with Thread.Sleep in it.

    Dumb question #3: Why start with 50? Why not try a small number first, like 2, that way you don't have to wait a long time to see the results and verify it works.
    Last edited by passel; May 21st, 2020 at 05:59 PM.
    "Anyone can do any amount of work, provided it isn't the work he is supposed to be doing at that moment" Robert Benchley, 1930

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,682

    Re: Simple exercise not working?

    As passel suggests, the issue is basically that you are tying up the UI thread for 50 seconds so it is not available to refresh the UI. Each thread can only do one thing at a time so, as long as the UI thread is tied up in your loop, most of which time is spent sleeping, then it can't refresh the view of your TextBox or anything else. If you were to minimise and restore your form or drag another form over it then you would see some nasty visual behaviour. There are a number of ways to "fix" this, some of which are better than others:

    1. Call Refresh on the TextBox as suggested, which will force a repaint of just that control.
    2. Call Application.DoEvents, which will raise and handle any pending events, including a Paint event on that TextBox.
    3. Call Task.Delay instead of Thread.Sleep. Task.Delay makes use of the Async/Await pattern so it won't freeze the UI, but it does complicate the code slightly.
    4. Get rid of the loop and start a Timer as suggested. You would then update the TextBox in the Tick event handler and stop the Timer after the desired number of Ticks.

    Options 1 and 2 are quick and dirty. Options 3 and 4 are more complex but are what you should do if you want to do it properly.

  4. #4

    Thread Starter
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    4,942

    Re: Simple exercise not working?

    Like I said, I'm not savvy with C#. Where in the code does it say I'm tying up the thread for 50 seconds?
    Blake

  5. #5
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,682

    Re: Simple exercise not working?

    Quote Originally Posted by blakemckenna View Post
    Like I said, I'm not savvy with C#.
    C# is basically the same as VB but with different syntax. You could do exactly what you're doing here in VB and it would look almost the same.
    Quote Originally Posted by blakemckenna View Post
    Where in the code does it say I'm tying up the thread for 50 seconds?
    You have a for loop that does 50 iterations and sleeps for 1 second on each iteration. 50 iterations x 1 second per iteration = 50 seconds.

  6. #6

    Thread Starter
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    4,942

    Re: Simple exercise not working?

    Got it...thanks for pointing that out. I've done this in VB.Net, however, I'm a VB.Net developer without a job and there isn't much call for VB.Net anymore. Consequently, I'm trying to learn C#.
    Blake

  7. #7
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,682

    Re: Simple exercise not working?

    I just copied your exact code and, exactly as suggested, the form froze for 50 seconds and then all the text appeared in the TextBox at once. Using option 3 from post #3, I added this:
    csharp Code:
    1. using System.Threading.Tasks;
    and changed this:
    csharp Code:
    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3.     interval = new TimeSpan(0, 0, 1);
    4.     PrintIt();
    5. }
    6. //
    7. //
    8. //
    9. private void PrintIt()
    10. {
    11.     text1.Text = "";
    12.     label1.Visible = true;
    13.  
    14.     for (int x = 0; x < 50; x++)
    15.     {
    16.         text1.Text += "Iteration " + (x + 1) + "\r\n";
    17.         Thread.Sleep(interval);
    18.     }
    19. }
    to this:
    csharp Code:
    1. private async void button1_Click(object sender, EventArgs e)
    2. {
    3.     interval = new TimeSpan(0, 0, 1);
    4.     await PrintIt();
    5. }
    6. //
    7. //
    8. //
    9. private async Task PrintIt()
    10. {
    11.     text1.Text = "";
    12.     label1.Visible = true;
    13.  
    14.     for (int x = 0; x < 50; x++)
    15.     {
    16.         text1.Text += "Iteration " + (x + 1) + "\r\n";
    17.         await Task.Delay(interval);
    18.     }
    19. }
    and it worked as expected. Using async/await keeps the UI thread responsive while asynchronous work is performed. You could have written almost exactly the same code in VB and had the same issue and fixed it in the same way.

  8. #8
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,682

    Re: Simple exercise not working?

    By the way, instead of this:
    csharp Code:
    1. interval = new TimeSpan(0, 0, 1);
    I would tend to use this:
    csharp Code:
    1. interval = TimeSpan.FromSeconds(1);
    It's more readable and self-documenting.

  9. #9
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,682

    Re: Simple exercise not working?

    Quote Originally Posted by blakemckenna View Post
    Got it...thanks for pointing that out. I've done this in VB.Net, however, I'm a VB.Net developer without a job and there isn't much call for VB.Net anymore. Consequently, I'm trying to learn C#.
    Sound reasoning. Just remember that, almost universally, the same principles apply in C# as in VB. Sometimes, a code conversion is nothing more than adding or removing semicolons and changing the case of a few keywords. There are some slightly greater differences here and there, e.g. C# events are attached and removed using += and -= and they are basically equivalent to AddHandler and RemoveHandler with their being no equivalent to WithEvents and Handles. You can generally ignore even that though, given that you're generally attaching event handlers via the designer. If you are ever confused in C#, ask yourself how you would do something in VB and the C# will almost certainly be almost exactly the same.

  10. #10

    Thread Starter
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    4,942

    Re: Simple exercise not working?

    Thanks jmc...
    Blake

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width