2015-11-04 70 views
0

我正在做一些操作,如讀取一個csv文件並轉換爲一個對象。它的所有工作正常,除了BusyIndi​​cator不可見即使busyindicator.Isbusy = true;BusyIndi​​cator不可見?

一切都在主線程上運行,所以我猜想當我讀取文件時,UI或主線程可能因爲它不可見而忙碌。

代碼:

private void ImportData(Dictionary<string, ImportFieldMap> mappedItems) 
    { 

     var fileBytes = fileBrowseCtrl.FileBytes; 
     var getDelimiter = string.IsNullOrEmpty(txeSeperator.Text) ? UtilFunctions.GetDefaultDeLimiter() : txeSeperator.Text.ToCharArray()[0]; 
     if (fileBytes == null) 
     { 
      MessageBox.Show(Uniconta.ClientTools.Localization.lookup("NoFilesSelected"), Uniconta.ClientTools.Localization.lookup("Error"), MessageBoxButton.OK); 
      return; 
     } 
     Encoding Coding = Encoding.Unicode; 
     if (ANSICodePage.IsUTF8(fileBytes)) 
      Coding = Encoding.UTF8; 
     else if (ANSICodePage.IsANSI(fileBytes)) 
     { 
      fileBytes = ANSICodePage.Convert2Unicode(fileBytes); 
      Coding = Encoding.Unicode; 
     } 

     try 
     { 
      busyIndicator.IsBusy = true; 
      CSVHelper csvData; 
      using (var reader = new StreamReader(new MemoryStream(fileBytes), Coding, true)) 
      { 
       csvData = CSVHelper.Load(reader, getDelimiter); 
      } 
      //Converting to UnicontaObject Code... 
     } 
     catch 
     { 
      MessageBox.Show(Uniconta.ClientTools.Localization.lookup("InvalidFileFormat"), Uniconta.ClientTools.Localization.lookup("Error"), MessageBoxButton.OK); 
      fileBrowseCtrl.ResetControl(); 
     } 
     finally 
     { 
      busyIndicator.IsBusy = false; 
     } 
    } 

有沒有一種方法,我可以在不同的線程seperately運行,這樣當函數被調用的UI顯示BusyIndi​​cator控件,並在後臺喜歡讀CSV並轉換爲對象的操作情況

我已經嘗試過使用BackgroundWorkerThread,但是是一個異步的,所以有沒有其他方式實現這一目標?

問候

+0

'BackgroundWorker'適合您的需求。然而,我沒有得到你的意思---但是它是一個異乎尋常的東西,所以還有什麼其他方法可以實現。您可以訂閱DoWork和RunWorkCompletedEvent。讀取並加載DoWork Handler中的CSV數據,並將結果返回到RunWorkCompletedEvent處理程序。另外,在RunWorkCompletedEvent處理程序中設置busyIndi​​cator.IsBusy = false。 – user1672994

回答

0

1. Multihreading

1.1 BackgroungWorker是好的。

1.2。另一種選擇是使用Dispatcher

每個WPF組件具有Dispatcher你可以用它來找回GUI線程:

// Get the dispatcher on the Gui thread 
Dispatcher dispatcher = window.Dispatcher; 

// use it on the worker thread to get back to GUI thread 
dispatcher.Invoke( 
() =>{ 
    busyIndicator.IsBusy = true; 
); 

2.更新GUI

你之所以在GUI中沒有改變,可能是因爲你的GUI屬性不會引發任何事件。

public bool IsBusy{ 
    get{ return isBusy; } 
    set{ 
     isBusy = value; 
     FirePropertyChange(); 
    } 
} 

而且INotifyPropertyChanged應在類hoding的IsBusy屬性來實現:

public class User : IDataErrorInfo, INotifyPropertyChanged 
{ 
    private void OnNotifyPropertyChange([CallerMemberName]string propName = null) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propName)); 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 

問候

相關問題