繁体   English   中英

Task.Factory.StartNew在控制台C#应用程序中不起作用

[英]Task.Factory.StartNew is not working in console c# application

我有一个控制台应用程序,它从Console.OpenStandardInput();中读取消息; 我正在完成一项任务。 但它似乎不起作用。

   static void Main(string[] args)
        {
    wtoken = new CancellationTokenSource();
            readInputStream = Task.Factory.StartNew(() =>
            {
                wtoken.Token.ThrowIfCancellationRequested();
                while (true)
                { 
                    if (wtoken.Token.IsCancellationRequested)
                    {
                        wtoken.Token.ThrowIfCancellationRequested();
                    }
                    else
                    {
                       OpenStandardStreamIn();
                    }
                }
            }, wtoken.Token
            );
     Console.ReadLine();
}

这是我的OpenStandardStreamIn函数

   public static void OpenStandardStreamIn()
        {
                Stream stdin = Console.OpenStandardInput();
                int length = 0;
                byte[] bytes = new byte[4];
                stdin.Read(bytes, 0, 4);
                length = System.BitConverter.ToInt32(bytes, 0);
                string input = "";
                for (int i = 0; i < length; i++)
                {
                    input += (char)stdin.ReadByte();
                }
                Console.Write(input);
            }

有什么帮助吗? 为什么它不能连续循环工作

您基本上在Console.ReadLine和您的任务之间有一个竞争条件。 他们两个都试图从标准输入中读取-我当然不知道从两个线程同时从标准输入中读取时应该期待什么,但这似乎值得避免。

您可以通过将任务更改为除了从标准输入中读取内容以外的其他方式来轻松地进行测试。 例如:

using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main()
    {
        var wtoken = new CancellationTokenSource();
        var readInputStream = Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
                Thread.Sleep(200);
            }
        }, wtoken.Token);
        Console.ReadLine();
    }
}

如果您的真实代码需要从标准输入中读取,则建议您将Console.ReadLine()更改为readInputStream.Wait() 如果您使用的是.NET 4.5,我还建议您使用Task.Run而不是Task.Factory.StartNew() ,只是为了提高可读性-假设您不需要TaskFactory.StartNew任何更深奥的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM