背景工作者在wpf中的工作事件中无法正常工作

时间:2014-02-06 06:04:04

标签: c# wpf backgroundworker

我已经阅读过这篇文章,但它对我没有帮助:

Background worker does not work properly in WPF

我在wpf(C#)中使用后台工作器,我想在阅读文本文件时显示“loading ....”但它没有显示。我的代码是:

    private delegate void upmdlg();
    private delegate void upmdlg2();

    private void callmetoread()
    {
        StreamReader str = new StreamReader("C:\\test.txt");
        while (!str.EndOfStream)
        {
            richTextBox1.AppendText(str.ReadToEnd());
        }
    }

    private void callmetochangelabel()
    {
        label1.Foreground = Brushes.Red;
        label1.Content = "loading ....";
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        label1.Foreground = Brushes.Yellow;
        label1.Content = "idle";

        BackgroundWorker bg = new BackgroundWorker();

        bg.DoWork += delegate(object s, DoWorkEventArgs args)
        {
            upmdlg mo = new upmdlg(callmetochangelabel);
            label1.Dispatcher.BeginInvoke(mo, DispatcherPriority.Normal);

            upmdlg mo2 = new upmdlg(callmetoread);
            richTextBox1.Dispatcher.BeginInvoke(mo2, DispatcherPriority.Normal);

        };
        bg.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs arg)
        {
            label1.Foreground = Brushes.Green;
            label1.Content = "done ....";
        };

        bg.RunWorkerAsync();
    }

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

尝试使用SynchronizationContext.Current Post执行UI代码。 这对我很有用:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        label1.Foreground = Brushes.Yellow;
        label1.Content = "idle";

        var context = SynchronizationContext.Current;

        BackgroundWorker bg = new BackgroundWorker();

        bg.DoWork += (o, args) => 
        {

            context.Post(state => callmetochangelabel(),null);
            context.Post(state => callmetoread(), null);
        };
        bg.RunWorkerCompleted += (o, args) => 
        {
            label1.Foreground = Brushes.Green;
            label1.Content = "done ....";
        };

        bg.RunWorkerAsync();
    }

BTW:描述SynchronizationContext如何工作的帖子:It's All About the SynchronizationContextUnderstanding SynchronizationContext