Using Dispatcher with thread

99封情书 提交于 2019-12-08 12:56:38

问题


I have a list of rtf strings that are needed to convert to html. I am using a richtextbox control to convert rtf to html. My problem is this

The solution should also work but how do i implement this solution in my code?

public string ConvertRtfToHtml(string rtfText)
    {

        try
        {
            var thread = new Thread(ConvertRtfInSTAThread);                
            var threadData = new ConvertRtfThreadData { RtfText = rtfText };
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start(threadData);

            try
            {
                thread.Join();
            }
            catch(ThreadStateException e){
                logger.Error("ThreadStateException " + e.Message);
            }
            catch (ThreadInterruptedException e) {
                logger.Error("ThreadInterruptedException " + e.Message);
            }                


            return threadData.HtmlText;

        }
        catch (Exception e){
            logger.Error("ConvertRtfToHtml: " + e.InnerException.Message);
            return "Error";
        }

    }

private void ConvertRtfInSTAThread(object rtf)
    {
        MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter(); 

        var threadData = rtf as ConvertRtfThreadData;

        try
        {
            threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
        }
        catch(Exception e){
            logger.Error("ConvertRtfInSTAThread: " + e.Message);
        }

    }

this markupconverter.convertrtftohtml uses richtextbox control.

Where do i fit the Dispatcher in above code?

 Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
Dispatcher.Run();

回答1:


I used it as follows

private void ConvertRtfInSTAThread(object rtf)
    {
        MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter(); 

        var threadData = rtf as ConvertRtfThreadData;

        try
        {
            threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);

            Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
            dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
            Dispatcher.Run();
        }
        catch(Exception e){
            logger.Error("ConvertRtfInSTAThread: " + e.Message);
        }

    }


来源:https://stackoverflow.com/questions/47047437/using-dispatcher-with-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!