2012-04-07 56 views
0

我試圖務實地打開指定的word文檔,然後等待用戶在繼續之前完成編輯打開的文檔。用戶通過關閉窗口指示他完成了。打開文檔並等待用戶完成編輯

但是下面的代碼將不起作用!它會一直工作,直到我對文檔進行任何編輯:除了等待文檔關閉的無限循環外,所有內容都會凍結。 我該如何解決這個問題?

bool FormatWindowOpen; 
    string FormattedText = ""; 
    MSWord.Application FormattingApp; 
    MSWord.Document FormattingDocument; 

    private List<string> ImportWords() 
    { 
     string FileAddress = FileDialogue.FileName; 
     FormattingApp = new MSWord.Application(); 
     FormattingDocument = FormattingApp.Documents.Open(FileAddress); 

     FormattingDocument.Content.Text = "Format this document so it contains only the words you want and no other formatting. \nEach word should be on its own line. \nClose the Window when you're done. \nSave the file if you plan to re-use it." + 
            "\n" + "----------------------------------------------------------" + "\n" + "\n" + "\n" + 
            FormattingDocument.Content.Text; //gets rid of formatting as well 
     FormattingApp.Visible = true; 
     FormattingApp.WindowSelectionChange += delegate { FormattedText = FormattingDocument.Content.Text; }; 
     FormattingApp.DocumentBeforeClose += delegate { FormatWindowOpen = false; }; 
     FormatWindowOpen = true; 

     for (; ;){ //waits for the user to finish formating his words correctly 
      if (FormatWindowOpen != true) return ExtractWords(FormattedText); 
     } 
    } 

回答

1

您的for循環很可能會凍結您的UI線程。在另一個線程中啓動您的for循環。

下面是一個使用Rx框架將異步數據流作爲返回值的示例。

private IObservable<List<string>> ImportWords() 
    { 
     Subject<List<string>> contx = new Subject<List<string>>(); 
     new Thread(new ThreadStart(() => 
      { 
       //waits for the user to finish formatting his words correctly 
       for (; ;) 
       { 
        if (FormatWindowOpen != true) 
        { 
         contx.OnNext(ExtractWords(FormattedText)); 
         contx.OnCompleted(); 
         break; 
        } 
       } 
      })).Start(); 
     return contx; 
    } 
+0

這仍然會導致for循環,因爲線程無法返回值,只是在Main和線程之間共享值會導致不斷檢查線程,直到完成爲止。 – Griffin 2012-04-08 00:20:01

+0

沒關係。我只是把除了for循環以外的所有東西放到另一個線程中,以避免返回一個值。謝謝! – Griffin 2012-04-08 00:24:42

+0

@格里芬:如果我的答案讓你解決你的問題,請你接受我的答案? - 您也可以使用事件或IObservable將您的值返回到主線程。 – caesay 2012-04-08 00:43:03