首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从后台工作人员更改TextBlock.Inlines

从后台工作人员更改TextBlock.Inlines
EN

Stack Overflow用户
提问于 2016-03-04 14:52:49
回答 2查看 148关注 0票数 0

有没有什么方法可以改变BackgroundWorker中的内联?

我尝试了以下几种方法:

代码语言:javascript
复制
private void test()
    {
        var rows = GetDataGridRows(dgVarConfig);
        foreach (DataGridRow r in rows)
        {
            TextBlock tb = cMatchEx.GetCellContent(r) as TextBlock;

            if (!syntaxWorker.IsBusy)
                syntaxWorker.RunWorkerAsync(new KeyValuePair<TextBlock, String>(tb, tb.Text));
        }
    }

    private void syntaxWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        if (e.Argument == null)
            Thread.Sleep(100);
        else
        {
            KeyValuePair<TextBlock, String> kvp = (KeyValuePair<TextBlock, String>)e.Argument;
            e.Result = new KeyValuePair<TextBlock, List<Run>>(kvp.Key, Syntax.Highlight(kvp.Value));
        }
    }


    private void syntaxWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Result != null)
        {
            KeyValuePair<TextBlock, List<Run>> kvp = (KeyValuePair<TextBlock, List<Run>>)e.Result;
            TextBlock tb = kvp.Key;
            tb.Text = "";
            kvp.Value.ForEach(x => tb.Inlines.Add(x));
        }
    }

和语法类:

代码语言:javascript
复制
public static class Syntax
{
    static Regex subFormula = new Regex(@"\w+\(\)");
    static Regex sapFormula = new Regex(@"\w+\(([^)]+)\)");
    static Regex strings = new Regex(@"\'[^']+\'");
    static Regex numerals = new Regex(@"\b[0-9\.]+\b");
    static Regex characteristic = new Regex(@"(?:)?\w+(?:)?");
    static Regex andOr = new Regex(@"( and )|( AND )|( or )|( OR )");
    static Regex not = new Regex(@"(not )|(NOT )");

    private static Brush[] colorArray;

    public static List<Run> Highlight(String input)
    {


        colorArray = new Brush[input.Length];

        for (int i = 0; i < input.Length; i++)
            colorArray[i] = Brushes.Black;

        //Reihenfolge beibehalten!!
        assignColor(Brushes.Blue, characteristic.Matches(input));
        assignColor(Brushes.Black, andOr.Matches(input));
        assignColor(Brushes.Black, numerals.Matches(input));
        assignColor(Brushes.Orange, strings.Matches(input));
        assignColor(Brushes.DeepPink, subFormula.Matches(input));
        assignColor(Brushes.Green, sapFormula.Matches(input));
        assignColor(Brushes.Green, not.Matches(input));


        int index = 0;

        List<Run> runList = new List<Run>();

        foreach (Char character in input)
        {
            runList.Add(new Run(character.ToString()) { Foreground = colorArray[index] });
            index++;
        }


        colorArray = null;
        return runList;
    }

    public static void Check(TextBlock textBlock)
    {

    }


    private static void assignColor(Brush brush, MatchCollection matchCollection)
    {
        foreach (Match match in matchCollection)
        {
            int start = match.Index;
            int end = start + match.Length;

            for (int i = start; i < end; i++)
            {
                colorArray[i] = brush;
            }
        }
    }
}

我总是收到这样的错误:The calling thread cannot access this object because a different thread owns it.

我尝试了许多不同的方法:返回进度已更改的runList,将静态语法类更改为普通类。但是什么都不起作用,总是同样的错误。

我也试着从后台工作人员那里调用它。这意味着调用

代码语言:javascript
复制
    List<Run> runList = Syntax.Highlight(kvp.Value);

this.Dispatcher.Invoke((Action)(() =>
    {
        runList.ForEach(x => publicRunList.Add(x));
    }));

有人知道问题出在哪里吗?

EN

回答 2

Stack Overflow用户

发布于 2016-03-04 14:58:26

使用

代码语言:javascript
复制
tb.Dispatcher.Invoke(() => {
    tb.Text = "";
    kvp.Value.ForEach(x => tb.Inlines.Add(x));
});

而不是

代码语言:javascript
复制
tb.Text = "";
kvp.Value.ForEach(x => tb.Inlines.Add(x));

Gui元素只能从GUI线程访问。使用Dispatcher.Invoke可确保调用的操作在其上运行。

您还将在Syntax.Highlight中创建Run对象。您还必须在Gui线程上创建Gui元素。因此您还应该将此调用包装在dispatcher invoke中:

代码语言:javascript
复制
e.Result = new KeyValuePair<TextBlock, List<Run>>(kvp.Key, Syntax.Highlight(kvp.Value));

这应该是可行的:

代码语言:javascript
复制
//this runs synchronously
kvp.Key.Dispatcher.Invoke(() => {
    e.Result = new KeyValuePair<TextBlock, List<Run>>(kvp.Key, Syntax.Highlight(kvp.Value));
});

//this runs asynchronously
kvp.Key.Dispatcher.BeginInvoke((Action)(() => {
    e.Result = new KeyValuePair<TextBlock, List<Run>>(kvp.Key, Syntax.Highlight(kvp.Value));
}));

这可能违背了您最初想要使用BackgroundWorker的目的。我建议更改Syntax.Highlight的接口,返回带有字符串和突出显示颜色的元组列表,然后在GUI线程上创建Run对象。

编辑

正如Gopichandar所指出的,使用BeginInvoke异步执行给定的操作,因此这将解决应用程序冻结的问题。不过,在将所有元素添加到Gui之前,仍然需要几秒钟的时间。

票数 1
EN

Stack Overflow用户

发布于 2016-03-04 16:51:38

在WPF中,只有UI元素所属的线程(即UI线程)可以与其通信。BackgroundWorker的DoWork部分在不同的线程中执行,因此不能做任何与UI相关的事情。同样的事情也适用于定时器而不是BackgroundWorkers。

但是如果您使用var worker = new BackgroundWorker {WorkerReportsProgress = true};创建BackgroundWorker,那么您可以为ProgressChanged设置一个事件处理程序。在您的_DoWork()中,您可以说:(sender as BackgroundWorker).ReportProgress,它将在原始线程中调用您的ProgressChanged事件处理程序,您可以在其中操作UI元素。

完整示例:http://www.wpf-tutorial.com/misc/multi-threading-with-the-backgroundworker/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35789795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档