0

我试图务实地打开一个指定的word文档,然后等待用户完成编辑打开的文档,然后再继续。用户通过关闭窗口来指示他完成了。

但是下面的代码不起作用!它一直有效,直到我对文档进行任何编辑:除了等待文档关闭的无限 for 循环之外,一切都冻结了。我该如何解决这个问题?

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);
        }
    }
4

1 回答 1

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;
    }
于 2012-04-07T22:42:41.013 回答