O
O
Ogoun Er2012-05-16 16:26:45
.NET
Ogoun Er, 2012-05-16 16:26:45

Confused about multithreading

Option one:

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Console.WriteLine("WTF");
                    Thread.Sleep(1000);
                }
            });
            Console.ReadKey();


Option two:
            Console.WriteLine("Start");
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Console.WriteLine("WTF");
                    Thread.Sleep(1000);
                }
            });
            Console.ReadKey();


In the first variant, nothing will be output to the console; in the second, a message will be displayed as required per second.
The behavior is the same in both debug and release versions.

Does anyone understand why adding output to the console in the main thread allows output in the child?
In MSDN'e write:

Thread safety
This type is safe for use in multithreaded programs.

Here is the complete compiled text of the program (in the version where the output does not work):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Start");
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Console.WriteLine("WTF");
                    Thread.Sleep(1000);
                }
            });
            Console.ReadKey();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bleykher, 2012-05-16
@bleykher

I copied your code, it works correctly, that is, it issues WTF once a second.
What do you compile?

I
ixSci, 2012-05-16
@ixSci

I don't know C#, but is there any method of forced flushing of the output stream buffer? If so, then try using it in a thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question