【问题标题】:Why my windows form freezes and deadlock?为什么我的窗体冻结和死锁?
【发布时间】:2014-11-07 01:37:47
【问题描述】:

对于我的生产者-消费者应用程序,我单击了按钮来触发它。然而它冻结了。该项目的基本思想是在单击开始按钮时查找队列中有多少个偶数。单击取消按钮将其停止。我想在控制台上打印结果。但两者都不起作用,这意味着没有输出(屏幕上为空)。可能是死锁?无论如何,屏幕冻结。

整个干净的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CancellationTokenStop
{
    public partial class Form1 : Form
    {
        public static BufferBlock<int> m_Queue = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1000 });
        private static int evenNumber;
        private static CancellationTokenSource cTokenSource;
        private static CancellationToken cToken;
        private static Object obj = new object();
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AllocConsole();
        public Form1()
        {
            InitializeComponent();
            AllocConsole();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
           cTokenSource.Cancel();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                cTokenSource = new CancellationTokenSource();
                cToken = cTokenSource.Token;
                var producer = Producer();
                var consumer = Consumer();

                Task.WhenAll(producer, consumer).Wait();
                Report();
            }
            catch (AggregateException ex)
            {
                Console.WriteLine(ex.InnerException);
                Console.Read();
            }
        }

        static async Task Producer()
        {
            for (int i = 0; i < 200; i++)
            {
                // Send a value to the consumer and wait for the value to be processed
                await m_Queue.SendAsync(i);
            }
            // Signal the consumer that there will be no more values
            m_Queue.Complete();
        }

        static async Task Consumer()
        {
            try
            {
                var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions
                {
                    MaxDegreeOfParallelism = 4
                };
                var consumerBlock = new ActionBlock<int>(x =>
                {
                    DoWork(x, cToken);
                    if (x % 2 == 0)
                        // Increment the counter in a thread-safe way
                        Interlocked.Increment(ref evenNumber);

                }, executionDataflowBlockOptions);

                // Link the buffer to the consumer
                using (m_Queue.LinkTo(consumerBlock, new DataflowLinkOptions { PropagateCompletion = true }))
                {
                    // Wait for the consumer to finish.
                    // This method will exit after all the data from the buffer was processed.
                    await consumerBlock.Completion;
                }
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }

        static void DoWork(int x, CancellationToken cToken)
        {
            cToken.Register(() =>
            {
                 Console.WriteLine("Stop at "+x);
            });
            Thread.Sleep(100);
        }

        public static void Report()
        {
             Console.WriteLine("There are {0} even numbers", evenNumber);
        }
    }
}

生产者部分很简单,它只是将数据发送到BufferBlock。消费者部分很复杂,使用ActionBlock并传递一个取消令牌。

预期结果存储在变量evenNumber 中。

【问题讨论】:

  • GUI 应用程序中的“冻结”或“死锁”几乎总是意味着您已经阻塞了程序中的主线程,即处理所有绘图和用户输入的主线程。如果您实际搜索网络或 StackOverflow,您会发现很多关于该主题的现有讨论,以及很好的解决方案。
  • 好吧,因为你特别说它应该 Wait()。 Task.WhenAll(生产者,消费者).Wait();阻止你的用户界面,如果你应该等待生产者和消费者的电话会更好
  • @RonaldEstacion,如果我删除Wait,则输出错误。
  • @HuiZhao 去寻找Task ContinueWith,你可以用它来链接动作,我还在安装我的VS,所以我不能给你提供模拟代码。

标签: c# winforms tpl-dataflow


【解决方案1】:

您在单击按钮时阻止了 UI,而您需要使用 .Wait 来代替 await

    private async void btnStart_Click(object sender, EventArgs e)
    {
        try
        {
            cTokenSource = new CancellationTokenSource();
            cToken = cTokenSource.Token;
            var producer = Producer();
            var consumer = Consumer();

            await Task.WhenAll(producer, consumer);
            Report();
        }
        catch (AggregateException ex)
        {
            Console.WriteLine(ex.InnerException);
            Console.Read();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多