WPF window image updating from menuitem but not when in while loop

前端 未结 1 1403
孤城傲影
孤城傲影 2020-12-21 18:49

Okay, this is a real head-scratcher:

If I select a menuitem that causes the image, that makes up the entire window (a writeableBitmap) to have some pixels drawn on i

相关标签:
1条回答
  • 2020-12-21 19:23

    What happened when you inserted a MessageBox into the processing and got the results you were expecting was that the UI thread had a chance to get 'caught up' while the MessageBox was open. So it created the 'illusion' that using an MessageBox suddenly made it work, but behind the scenes it was just threads sorting themselves out and clearing their instruction queues.

    To create the same effect programmatically, you can update your bitmap with a method like this (ETA: requires .NET 4.5 Framework)...

        public void UpdateBitmap()
        {
            WriteableBitmap writeableBitmap = new WriteableBitmap
                                    (100, 100, 96, 96, PixelFormats.Bgr32, null);
            writeableBitmap.Dispatcher.InvokeAsync(() =>
                {
                    Console.WriteLine("work goes here");
                });
        }
    

    This runs the operation asynchronously on the thread that the bitmap's dispatcher is associated with and will give the UI a chance to catch up. Depending upon the payload of your 'DrawDinos2d' method, you MIGHT have to migrate the processing to a background thread and feed it to the UI thread on a piece-by-piece basis. But start with this approach first.

    ETA: In a .NET 4.0 framework, the counterpart to the above looks like this...

        public void UpdateBitmap()
        {
            object[] objs = new object[] {null};
            WriteableBitmap writeableBitmap = new WriteableBitmap(
                 100, 100, 96, 96, PixelFormats.Bgr32, null);
            writeableBitmap.Dispatcher.BeginInvoke((SendOrPostCallback)delegate
                {
                    Console.WriteLine(@"work goes here");
                }, objs);
        }
    

    The docs read "Executes the specified delegate asynchronously with the specified arguments on the thread that the System.Windows.Threading.Dispatcher was created on."

    0 讨论(0)
提交回复
热议问题