Smart Man
Smart Man

Reputation: 325

Background worker does not work properly in do work event in wpf

i have read this post but it did not help me :

Background worker does not work properly in WPF

I am using a background worker in wpf(C#) and i want when reading text file , it shows the "loading ...." but it does not show. my code is :

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

Thanks for any help.

Upvotes: 0

Views: 301

Answers (1)

Stadub Dima
Stadub Dima

Reputation: 858

Try with SynchronizationContext.Current Post for execution UI code. This works for me well:

    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: Posts that describes how SynchronizationContext works: It's All About the SynchronizationContext and Understanding SynchronizationContext

Upvotes: 1

Related Questions