Console application (C #) gets stuck during interaction

I am writing a console application that does a certain job of the scheduler and writes the output to the console. Everything is fine, but when I click on the console, it stops working and waits for my right click. After that, he continues to work.

I thought that he simply did not write the text to the console and did what was needed, but no, he was waiting for my interaction. I can rewrite this code in WinForms or WPF, but I think it can be solved differently. Here is my code

    static void Main(string[] args)
    {
        Console.WriteLine("Started...");
        var timer = new System.Timers.Timer(1000);
        timer.Elapsed += timer_Elapsed;
        timer.Start();

        Console.ReadLine();
    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Writing to file " + DateTime.Now.ToString());
        System.IO.File.AppendAllLines(@"C:\Temp\log.txt", 
          new[] { DateTime.Now.ToString()});
    }

After clicking on the console, it pauses the time it takes to add the log.txt file. Any ideas how to fix this? Thanks.

+6
source share
2 answers

, , . , Console.Write. Console (Console.Out), TextWriter (source). , "".

, . , :

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            Console.WriteLine("Writing to file " + DateTime.Now.ToString());
        });
        System.IO.File.AppendAllLines(@"C:\Temp\log.txt", 
          new[] { DateTime.Now.ToString()});
    }

, , , . , , ThreadPool.

, , TaskScheduler, SequentialScheduler

    static TaskFactory factory = new TaskFactory(new SequentialScheduler());

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        factory.StartNew(() =>
        {
            Console.WriteLine("Writing to file " + DateTime.Now.ToString());
        });
        System.IO.File.AppendAllLines(@"C:\Temp\log.txt", 
         new[] { DateTime.Now.ToString()});
    }

ThreadPool. , , , , .

+6

, , - . (, ).

, , . , , , - , .

:

    static ConcurrentQueue<string> consoleQueue = new ConcurrentQueue<string>();
    static ManualResetEventSlim itemEnqueuedEvent = new ManualResetEventSlim();

    static void WriteToConsoleLoop(object state)
    {
        var token = (CancellationToken)state;
        while (!token.IsCancellationRequested)
        {
            string entry;
            while (consoleQueue.TryDequeue(out entry))
            {
                Console.WriteLine(entry);
            }
            try
            {
                itemEnqueuedEvent.Wait(token);
                itemEnqueuedEvent.Reset();
            }
            catch (OperationCanceledException)
            {
                break;
            }
        }
    }

    static void WriteToConsole(string entry)
    {
        consoleQueue.Enqueue(entry);
        itemEnqueuedEvent.Set();
    }

    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        // Background or foreground, depends on how vital it is
        // to print everything in the queue before shutting down.
        var thread = new Thread(WriteToConsoleLoop) { IsBackground = true };
        thread.Start(cts.Token);

        WriteToConsole("Started...");

        // Do your stuff...

        cts.Cancel();
    }
+3

Source: https://habr.com/ru/post/1016567/


All Articles