0

I'm beginner in C#. And I don't understand why next two examples are giving different results. I'm using microsoft example in msdn. In first example it displays one number in the textbox. In second example it displays all numbers from 0 to 1000 for each thread.

First example:

    delegate void SetTextCallback(object text);

    private void WriteString(object text)
    {

        if (this.textBox1.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(WriteString);
            this.BeginInvoke(d, new object[] { text });
        }
        else
        {
            for (int i = 0; i <= 1000; i++)
            {
                textBox1.Text = text.ToString();
            }

        }

    }

Second example:

    private void MyApp_Load(object sender, EventArgs e)
    {
        System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

    }

    private void WriteString(object text)
    {
        for (int i = 0; i <= 1000; i++)
        {
            textBox1.Text = text.ToString();
        }
    }

And method which calls these examples

    private void button1_Click(object sender, EventArgs e)
    {

        Thread th_1 = new Thread(WriteString);
        Thread th_2 = new Thread(WriteString);
        Thread th_3 = new Thread(WriteString);
        Thread th_4 = new Thread(WriteString);

        th_1.Priority = ThreadPriority.Highest; 
        th_2.Priority = ThreadPriority.BelowNormal; 
        th_3.Priority = ThreadPriority.Normal; 
        th_4.Priority = ThreadPriority.Lowest; 

        th_1.Start("1");
        th_2.Start("2");
        th_3.Start("3");
        th_4.Start("4");

        th_1.Join();
        th_2.Join();
        th_3.Join();
        th_4.Join();
    }
tnw
  • 13,521
  • 15
  • 70
  • 111
Boris Mitioglov
  • 1,092
  • 4
  • 16
  • 32
  • 1
    I must be missing something. Both examples _seem_ like they would only ever have a single number written to the text field (either "1", "2", "3", or "4") and never the set from 0 to 1000, nor would it show multiple numbers at once. Unless maybe it has to do with inconsistent behaviour from writing to the `Text` property from a background thread? – Chris Sinclair Mar 22 '13 at 20:45
  • 1
    The second example summons Cthulhu by accessing GUI elements directly from threads. Use System.Console.WriteLine() or similar to actually compare them. – DasKrümelmonster Mar 22 '13 at 20:49
  • Hi @DasKrümelmonster! How to use System.Console.WriteLine() in Win.Forms Application? – Boris Mitioglov Mar 22 '13 at 21:42
  • Did you try it? VS displays the output in the bottom right pane by default. (At least it works for me, If not see here: http://stackoverflow.com/questions/5301232/seeing-the-consoles-output-in-visual-studio-2010 ) – DasKrümelmonster Mar 22 '13 at 21:57
  • @goodspeed: You cannot use console.writeline() as the name of the class indicates, its only used with Console apps. However, an equivalent thing in Winforms is to use MessageBox.Show(). Example: Console.Writeline(resultString) as MessageBox.Show(Result: {0}", resultString). – Jasmine Mar 22 '13 at 21:57
  • Typo: MessageBox.Show("Result: {0}", resultString); – Jasmine Mar 22 '13 at 22:05
  • @Divine no, I can use. Now i have added View -> Output and i see my data in output window just using Console.Write(text.ToString()); – Boris Mitioglov Mar 22 '13 at 22:21
  • -1 for posting the same question twice – Frank Schmitt Mar 23 '13 at 07:57
  • @goodspeed: Thank you so much, thats a new learning for me :) Cheers :) – Jasmine Mar 23 '13 at 08:28
  • @FrankSchmitt it's not a same question, guys – Boris Mitioglov Mar 23 '13 at 12:45

1 Answers1

0

Well I analyzed in my VS. I am also new to C#. But what I could infer is the following:

Program 1:

Begin Invoke is aynschronous way of calling a method. Thus it shows only one result at the end. If you have slowly did F11 in VS and observe, not really everytime you get the result 4. But sometime you get 3 too when you do F11 and go step by step at certain places(I mean delaying), due to multi threading. You should remember that, multi threading always never behave in same manner all the time, which means suppose if an application or module in multithreading gives you one result at a time, two times, and 10 times, you cannot be sure that its the correct or optimized code. Because at client environment, due to its own behavior, it can lead to different results which may potentially be unnoticed while debugging or it wont even happen. I read it in a nice blog.

Program 2:

Since its multithreading, I could see the behavior of different threads getting invoked at different time, and as it does the job, I see the textboxes are getting updated quickly in fraction of seconds thats not possible for an human eye to notice, but final result, a single number is displayed. Also you do check for cross thread calls )When you do step into every line of code using F11, you will find this behavior and understand well ) and you order not to catch it. This makes the threads to work together in second case.

This is my inference, but I can say, pretty corny! I don't claim this with confidence, but just my observation :)

Let some great folks chime in with their views to help us :)

Cheers

Jasmine
  • 5,186
  • 16
  • 62
  • 114
  • Thanks for your great answer. As i understand program1 displays only one number one time... but why.. Can i display all 1000 numbers from each thread in program one? – Boris Mitioglov Mar 22 '13 at 21:32
  • Well I am really sorry, I am not able to do what you just asked :( I would be happy too if someone help us both :) Cheers – Jasmine Mar 22 '13 at 21:59
  • richTextBox1.AppendText(text.ToString());@Divine if you add this instead of textBox1.Text = text.ToString(); you will see that program1 displays all numbers for each thread. I think it's like synchronized in Java. In program2 threads displays all numbers at the same time because there is not "synchronized" in code. – Boris Mitioglov Mar 22 '13 at 22:16