优先级线程未按预期顺序完成工作

时间:2018-05-06 17:35:41

标签: c# wpf multithreading

在学校我获得了一项任务,即构建一个简单的应用程序来展示线程如何优先处理工作。问题是我开火的线程并没有坚持优先级设置并随机完成(或者看起来如此)。

我主窗口的代码:

namespace ThreadsShowtime
{
    public partial class MainWindow : Window
    {
        private SuperThread _lowest;
        private SuperThread _below;
        private SuperThread _normal;
        private SuperThread _above;
        private SuperThread _highest;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            _lowest = new SuperThread(ThreadPriority.Lowest, elipseLowest, Dispatcher, lowestLbl);
            _below = new SuperThread(ThreadPriority.BelowNormal, elipseBelow, Dispatcher, belowLbl);
            _normal = new SuperThread(ThreadPriority.Normal, elipseNormal, Dispatcher, normalLbl);
            _above = new SuperThread(ThreadPriority.AboveNormal, elipseAbove, Dispatcher, aboveLbl);
            _highest = new SuperThread(ThreadPriority.Highest, elipseHighest, Dispatcher, highestLbl);

            _lowest.Start();
            _below.Start();
            _normal.Start();
            _above.Start();
            _highest.Start();
        }
    }
}

和SuperThread类代码:

namespace ThreadsShowtime
{
    public class SuperThread
    {
        private readonly Stopwatch _stopwatch;
        public readonly Thread Thread;

        public SuperThread(ThreadPriority thp, Shape sh, Dispatcher dispatcher, ContentControl lbl)
        {
            Thread = new Thread(() => DummyMethod(dispatcher, sh, lbl)) {Priority = thp};
            _stopwatch = new Stopwatch();
        }

        public long Elapsed { get; private set; }
        public double ElapsedSeconds => Elapsed / 1000.0;


        private void DummyMethod(Dispatcher dispatcher, Shape sh, ContentControl lbl)
        {
            _stopwatch.Start();
            dispatcher.Invoke(() =>
            {
                sh.Fill = Brushes.GreenYellow;
            }, DispatcherPriority.Normal);    

            for (var idx = 0; idx < 30000; idx++) Console.WriteLine(idx);

            dispatcher.Invoke(() =>
            {
                sh.Fill = Brushes.OrangeRed;
            }, DispatcherPriority.Normal);

            _stopwatch.Stop();
            Elapsed = _stopwatch.ElapsedMilliseconds;

            dispatcher.Invoke(() =>
            {
                lbl.Content = ElapsedSeconds;
            }, DispatcherPriority.ContextIdle);

        }

        public void Start()
        {
            Thread.Start();
        }
    }
}

此应用程序的输出如下所示: Output

为什么会这样? 非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:2)

由于dispatcher.Invoke()Console.WriteLine(),您的代码实际上是单线程的。你看到的是排队线程的稍微不可预知的结果。那些队列不是FIFO。

要查看正确的效果,请对一些纯粹受CPU限制的代码进行基准测试,例如Sort()。确保它们运行&gt; 200毫秒,较小的运行是没有意义的。