简体   繁体   中英

How to perform an async UI update in C# WPF?

I have a simple C# .NET WPF app that should display all pictures of a folder, each for half a second using an image element. PollPic is a property (of variable pollPic). currImageFilename was declared above. I aimed to use Invoke/BeginInvoke in order to update the UI. The function where this code belongs to is a async function, that is called (with await) from a button click event.

When I have 6 pictured in the folder, each has been read and and sleep was called 6 times but only the last picture was displayed in the end. Where is my general thinking mistake here?

Thanks everybody.

       if (picPath != "")
        {
            string[] pollPicList = Directory.GetFiles(picPath);
            if (pollPicList.Length > 0)
            {
                for (int i = 0; i < pollPicList.Length; i++)
                {
                    currImageFilename = pollPicList[i];
                    PollPic = new BitmapImage(new Uri(currImageFilename));
                    this.Dispatcher.BeginInvoke(new Action(() => ShowDetectPic(PollPic)));
                    System.Threading.Thread.Sleep(500);

                }
            }
        }

Unsuccessfully tried to use Task.Run instead. Also not working Task t1 = new Task(() => ShowDetectPic(PollPic));

You can't sleep the GUI thread or nothing will render. Your async code needs to be the waiting, not whatever else it is you're doing there.

    async ... Function()
    {
        string[] pollPicList = Directory.GetFiles(picPath);
        if (pollPicList.Length > 0)
        {
            for (int i = 0; i < pollPicList.Length; i++)
            {
                currImageFilename = pollPicList[i];
                PollPic = new BitmapImage(new Uri(currImageFilename));
                ShowDetectPic(PollPic);
                await Task.Delay(500);
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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