Console.ReadKey()不起作用

Gre*_*ndy 5 .net c#

请看原始的Microsoft示例.

在第二个示例中,我们找到以下代码:

// The simplest UI thread ever invented.
Task.Run(() =>
{
    if (Console.ReadKey().KeyChar == 'c')
        cts.Cancel();
});
Run Code Online (Sandbox Code Playgroud)

(运行此代码需要完整代码:)

static int inputs = 2000;
static void Main(string[] args)
{
    // The token source for issuing the cancelation request.
    CancellationTokenSource cts = new CancellationTokenSource();

    // A blocking collection that can hold no more than 100 items at a time.
    BlockingCollection<int> numberCollection = new BlockingCollection<int>(100);

    // Set console buffer to hold our prodigious output.
    //Console.SetBufferSize(80, 2000);

    // The simplest UI thread ever invented.
    Task.Run(() =>
    {
        if (Console.ReadKey().KeyChar == 'c')
            cts.Cancel();
        else
        {
            Debugger.Break();
        }
    });

    // Start one producer and one consumer.
    Task.Run(() => NonBlockingConsumer(numberCollection, cts.Token));
    Task.Run(() => NonBlockingProducer(numberCollection, cts.Token));

    Console.WriteLine("Press the Enter key to exit.");
    Console.ReadLine();
}

static void NonBlockingConsumer(BlockingCollection<int> bc, CancellationToken ct)
{
    // IsCompleted == (IsAddingCompleted && Count == 0)
    while (!bc.IsCompleted)
    {
        int nextItem = 0;
        try
        {
            if (!bc.TryTake(out nextItem, 0, ct))
            {
                Console.WriteLine(" Take Blocked");
            }
            else
                Console.WriteLine(" Take:{0}", nextItem);
        }

        catch (OperationCanceledException)
        {
            Console.WriteLine("Taking canceled.");
            break;
        }

        // Slow down consumer just a little to cause
        // collection to fill up faster, and lead to "AddBlocked"
        Thread.SpinWait(500000);
    }

    Console.WriteLine("\r\nNo more items to take. Press the Enter key to exit.");
}

static void NonBlockingProducer(BlockingCollection<int> bc, CancellationToken ct)
{
    int itemToAdd = 0;
    bool success = false;

    do
    {
        // Cancellation causes OCE. We know how to handle it.
        try
        {
            // A shorter timeout causes more failures.
            success = bc.TryAdd(itemToAdd, 2, ct);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Add loop canceled.");
            // Let other threads know we're done in case
            // they aren't monitoring the cancellation token.
            bc.CompleteAdding();
            break;
        }

        if (success)
        {
            Console.WriteLine(" Add:{0}", itemToAdd);
            itemToAdd++;
        }
        else
        {
            Console.Write(" AddBlocked:{0} Count = {1}", itemToAdd.ToString(), bc.Count);
            // Don't increment nextItem. Try again on next iteration.

            //Do something else useful instead.
            UpdateProgress(itemToAdd);
        }

    } while (itemToAdd < inputs);

    // No lock required here because only one producer.
    bc.CompleteAdding();
}

static void UpdateProgress(int i)
{
    double percent = ((double)i / inputs) * 100;
    Console.WriteLine("Percent complete: {0}", percent);
}
Run Code Online (Sandbox Code Playgroud)

该代码应该做的是完全清楚的:它应该在按下时中断c,但它不起作用.相反,它一直运行到最后要求关闭Enter.

我们该如何解决这个问题?

这似乎是一个线程问题,但它是.net4.5的演示,代码无效.

'c'的KeyPress没有设置CancelationToken.

Pat*_*man 4

你对这个例子的错误是完全正确的。它只是坏了。

它不起作用的原因是它不等待 s 完成Task,而是等待Console.ReadLine. 这将修复它:

代替:

Task.Run(() => NonBlockingConsumer(numberCollection, cts.Token));
Task.Run(() => NonBlockingProducer(numberCollection, cts.Token));
Run Code Online (Sandbox Code Playgroud)

和:

Task t1 = Task.Run(() => NonBlockingConsumer(numberCollection, cts.Token));
Task t2 = Task.Run(() => NonBlockingProducer(numberCollection, cts.Token));

Task.WaitAll(t1, t2);
Run Code Online (Sandbox Code Playgroud)

  • 这很奇怪。我确实尝试过这个,但它不起作用。现在我再次输入它,它可以工作了。谢谢你。 (2认同)