0

有什么方法可以从 BackgroundWorker 更改内联?

我尝试了以下方法:

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

和语法类:

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,将静态语法类更改为普通类..但没有任何效果,它总是同样的错误。

我还尝试从 Backgroundworker 调用它。这意味着调用

    List<Run> runList = Syntax.Highlight(kvp.Value);

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

有人知道这个问题吗?

4

2 回答 2

1

利用

tb.Dispatcher.Invoke(() => {
    tb.Text = "";
    kvp.Value.ForEach(x => tb.Inlines.Add(x));
});

代替

tb.Text = "";
kvp.Value.ForEach(x => tb.Inlines.Add(x));

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

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

e.Result = new KeyValuePair<TextBlock, List<Run>>(kvp.Key, Syntax.Highlight(kvp.Value));

这应该有效:

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

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

编辑

正如 Gopichandar 所指出的,使用BeginInvoke异步执行给定的动作,这样就可以解决应用程序的冻结问题。不过,将所有元素添加到 Gui 仍需要几秒钟的时间。

于 2016-03-04T06:58:25.647 回答
0

在WPF中,只有UI元素所属的线程(即UI线程)才能与之通信。BackgroundWorker 的 DoWork 部分在不同的线程中执行,因此无法执行任何与 UI 相关的操作。Timers 而不是 BackgroundWorkers 也是如此。

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

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

于 2016-03-04T08:51:37.943 回答