Пользовательский интерфейс зависает при нажатии кнопки в WPF - невозможно отобразить прогресс в прогресс-баре - PullRequest
0 голосов
/ 21 октября 2019

когда я щелкаю событие click_button, весь пользовательский интерфейс (все компоненты, окна) зависает. Индикатор выполнения не обновляется, пока выполняется задание. Вместо этого, когда все загрузки завершены, индикатор выполнения обновляет значение до 100%.

private void Click_Button(object sender, RoutedEventArgs e)
        {
            Thread t = new Thread(()=>Click_ButtonAsync(sender, e));
            //t.IsBackground = true;
            t.Start();

            Photos.Path = (((sender as Button).Parent as StackPanel).Parent as Expander).Name.ToString();
        }

код для загрузки изображений в хранилище BLOB-объектов Azure

 private void  Click_ButtonAsync(object sender, RoutedEventArgs e)
        {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate ()
                {
                    progress.Value = 0;

                    System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
                    var result = dlg.ShowDialog();

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {

                        string img;
                        double ct = 0;
                        var dir = dlg.SelectedPath;
                        var imageList =
                            new ConcurrentBag<string>(
                                Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
                                    .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif")));
                        double count = (double)imageList.Count();
                        while (imageList.TryTake(out img))
                        {
                            System.Diagnostics.Debug.WriteLine(img);
                            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString("DefaultEndpointsProtocol=https;AccountName=albus;AccountKey=;EndpointSuffix=core.windows.net");

                            // Create a blob client for interacting with the blob service.
                            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                            CloudBlobContainer container = blobClient.GetContainerReference("containerservice");

                            CloudBlobDirectory eventurl = container.GetDirectoryReference("sampledir/" + (((sender as Button).Parent as StackPanel).Parent as Expander).Name.ToString() + "/EventImages");

                            //CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);
                            string imageName = System.IO.Path.GetFileName(img);
                            CloudBlockBlob blockBlob = eventurl.GetBlockBlobReference(imageName);
                            Task t = blockBlob.UploadFromFileAsync(img, FileMode.Open);
                            t.Wait();
                            ct++;
                            //Dispatcher.Invoke(new Action(() => this.progress.Value = (ct / count) * 100), null);
                            progress.Dispatcher.Invoke(
             new UpdateTextCallback(this.UpdateText),
             new object[] { ct, count }
         );

                            Thread.Sleep(2000);

                        }
                    }
                }));
        }

обновление индикатора выполнения

 private void UpdateText(double ct, double count)
        {
            progress.Value = (ct / count) * 100; // Do all the ui thread updates here

        }
...