2016-10-05 93 views
-2

我需要在WPF wizardcontrol上加載覆蓋。我正在使用wpf擴展seamlit中的busyIndi​​cator工具。使用異步等待WPF WizardControl自定義繁忙覆蓋

async await的代碼有效,但gui線程鎖定。我正在嘗試在等待呼叫功能時添加請稍候消息

private async void Button1_Click(object sender, RoutedEventArgs e) 
     { 
     BusyIndicator.IsBusy = true; 
     BusyIndicator.IsEnabled = true; 
     BusyIndicator.BusyContent = "Please wait while Site is provisioned"; 

          await Task.Run(() => 
          { 
           LongRunningFunction(); 
          }); 

     BusyIndicator.IsBusy=false; 
     } 

BusyIndi​​cator的XAML如下所示。

<xctk:BusyIndicator x:Name="BusyIndicator" IsBusy="False" BusyContent="Please Wait"> 

</xctk:BusyIndicator> 

的LonRunningFunction是一個Web服務調用不更新用戶界面只返回一個布爾值

public static bool LongRunningFunction(string URL) 
     { 

      bool IsPresent = CallWebservice() 
      return IsPresent; 
     } 

問題

1)BusyIndi​​cator控件似乎沒有異步調用之前解僱,而不是當LongRunning任務完成時它似乎是火災

2)什麼是使用async和await時調用gui覆蓋的正確過程。

+0

您是否嘗試過使用'ThreadPool'而不是等待?麻煩的是,如果你正在操縱那個longRunningTask中的任何UI元素,你需要使用調度器,[Here](http://stackoverflow.com/a/37483878/2029607)就是你如何在你的代碼中使用它。 – XAMlMAX

+0

@XAMlMAX他*使用線程池。 'Task.Run'在線程池線程中調度工作。 – Servy

+0

沒有看到'LongRunningFunction',就沒有辦法知道代碼不工作的原因。顯然它正在做*它不應該做的事情,但我們無法知道是什麼。 – Servy

回答

0

這是我解決異步調用問題的方式。
語境:
這裏我使用MvvMWPF

using System.Threading; 
using System.Threading.Tasks; 
using System.Windows.Data; 
using System.Windows.Input; 
using System.Windows.Threading; 
class VM 
    { 
     Dispatcher _dispatcher = Dispatcher.CurrentDispatcher; 
     //Time consuming operation 
     private void LongTask() 
     { 
      Thread.Sleep(5000); 
      //in here if you need to send something to the UI thread like an event use it like so: 
      _dispatcher.Invoke(new Action(() => 
      { 
       //some code here to invoke an event 
       if (ComponentsLoaded != null) 
        ComponentsLoaded(this, new EventArgs { }); 
      })); 
     } 

     private ICommand _command; 
     //This is the command to be used instead of click event handler 
     public ICommand Command 
     { 
      get { return _command; } 
      private set { _command = value; } 
     } 
     //method associated with ICommand 
     void commandMethod(object parameter) 
     { 
      Busy = true; 
      ThreadPool.QueueUserWorkItem(new WaitCallback(multiThreadTask)); 
      Busy = false; 
     } 
     //the task to be started on another thread 
     void multiThreadTask(object parameter) 
     { 
      LongTask(); 
     } 

     public event EventHandler ComponentsLoaded; 
    } 

工作時,向您展示良好實踐這就是在WPF多線程工作時,我使用。
你仍然可以在代碼隱藏中使用它,只需要例示Dispatcher,你很好。
如果您需要更多信息,請告訴我們。 HTH