Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 455107
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T22:20:14+00:00 2026-05-12T22:20:14+00:00

I’m creating a backup utility in WPF and have a general question about threading

  • 0

I’m creating a backup utility in WPF and have a general question about threading:

In the method backgroundWorker.DoWork(), the statement Message2.Text = “…” gives the error “The calling thread cannot access this object because a different thread owns it.“.

Is there no way for me to directly access the UI thread within backgroundWorker.DoWork(), i.e. change text in a XAML TextBox at that point? Or do I need to store all display information in an internal variable, and then display it in backgroundWorker.ProgressChanged(), as I had to do with e.g. percentageFinished?

XAML:

<Window x:Class="TestCopyFiles111.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1"  Height="350" Width="525">
    <DockPanel LastChildFill="True" HorizontalAlignment="Left" VerticalAlignment="Top"
                Margin="10">

        <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
            <Button x:Name="Button_Start" 
                    HorizontalAlignment="Left"  
                    DockPanel.Dock="Top" 
                    Content="Start Copying" 
                    Click="Button_Start_Click" 
                    Height="25" 
                    Margin="0 0 5 0"
                    Width="200"/>
            <Button x:Name="Button_Cancel" 
                    HorizontalAlignment="Left"  
                    DockPanel.Dock="Top" 
                    Content="Cancel" 
                    Click="Button_Cancel_Click" 
                    Height="25" 
                    Width="200"/>
        </StackPanel>

        <ProgressBar x:Name="ProgressBar"
                     DockPanel.Dock="Top" 
                     HorizontalAlignment="Left"
                    Margin="0 10 0 0"
                    Height="23"
                     Width="405"
                     Minimum="0"
                     Maximum="100"
                     />

        <TextBlock DockPanel.Dock="Top" x:Name="Message" Margin="0 10 0 0"/>
        <TextBlock DockPanel.Dock="Top" x:Name="CurrentFileCopying" Margin="0 10 0 0"/>
        <TextBlock DockPanel.Dock="Top" x:Name="Message2" Margin="0 10 0 0"/>
    </DockPanel>
</Window>

code-behind:

using System.Windows;
using System.ComponentModel;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System;

namespace TestCopyFiles111
{
    public partial class Window1 : Window
    {
        private BackgroundWorker backgroundWorker;

        float percentageFinished = 0;
        private int totalFilesToCopy = 0;
        int filesCopied = 0;

        string currentPathAndFileName;

        private List<CopyFileTask> copyFileTasks = new List<CopyFileTask>();
        private List<string> foldersToCreate = new List<string>();

        public Window1()
        {
            InitializeComponent();
            Button_Cancel.IsEnabled = false;
            Button_Start.IsEnabled = true;
            ProgressBar.Visibility = Visibility.Collapsed;

        }

        private void Button_Start_Click(object sender, RoutedEventArgs e)
        {
            Button_Cancel.IsEnabled = true;
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.WorkerSupportsCancellation = true;
            ProgressBar.Visibility = Visibility.Visible;

            AddFilesFromFolder(@"c:\test", @"C:\test2");

            Message.Text = "Preparing to copy...";

            MakeSureAllDirectoriesExist();

            CopyAllFiles();

        }


        void AddFilesFromFolder(string sourceFolder, string destFolder)
        {
            if (!Directory.Exists(destFolder))
                Directory.CreateDirectory(destFolder);
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(destFolder, name);
                copyFileTasks.Add(new CopyFileTask(file, dest));
                totalFilesToCopy++;
            }
            string[] folders = Directory.GetDirectories(sourceFolder);
            foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                string dest = Path.Combine(destFolder, name);
                foldersToCreate.Add(dest);
                AddFilesFromFolder(folder, dest);
            }
        }

        void MakeSureAllDirectoriesExist()
        {
            foreach (var folderToCreate in foldersToCreate)
            {
                if (!Directory.Exists(folderToCreate))
                    Directory.CreateDirectory(folderToCreate);
            }
        }

        void CopyAllFiles()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.WorkerSupportsCancellation = true;

            backgroundWorker.DoWork += (s, args) =>
            {
                filesCopied = 0;
                foreach (var copyFileTask in copyFileTasks)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        args.Cancel = true;
                        return;
                    }

                    DateTime sourceFileLastWriteTime = File.GetLastWriteTime(copyFileTask.SourceFile);
                    DateTime targetFileLastWriteTime = File.GetLastWriteTime(copyFileTask.TargetFile);

                    if (sourceFileLastWriteTime != targetFileLastWriteTime)
                    {
                        Message2.Text = "dates are not the same";
                    }
                    else
                    {
                        Message2.Text = "dates are the same";
                    }

                    if (!File.Exists(copyFileTask.TargetFile))
                        File.Copy(copyFileTask.SourceFile, copyFileTask.TargetFile);

                    currentPathAndFileName = copyFileTask.SourceFile;

                    UpdatePercentageFinished();
                    backgroundWorker.ReportProgress((int)percentageFinished);

                    filesCopied++;
                }

            };

            backgroundWorker.ProgressChanged += (s, args) =>
            {
                percentageFinished = args.ProgressPercentage;
                ProgressBar.Value = percentageFinished;
                Message.Text = percentageFinished + "% finished";
                CurrentFileCopying.Text = currentPathAndFileName;
            };

            backgroundWorker.RunWorkerCompleted += (s, args) =>
            {
                Button_Start.IsEnabled = true;
                Button_Cancel.IsEnabled = false;
                ProgressBar.Value = 0;
                UpdatePercentageFinished();
                CurrentFileCopying.Text = "";

                if (percentageFinished < 100)
                {
                    Message.Text = String.Format("cancelled at {0:0}% finished", percentageFinished);
                }
                else
                {
                    Message.Text = "All files copied.";
                }
            };

            backgroundWorker.RunWorkerAsync();
        }

        void UpdatePercentageFinished()
        {
            percentageFinished = (filesCopied / (float)totalFilesToCopy) * 100f;
        }


        class CopyFileTask
        {
            public string SourceFile { get; set; }
            public string TargetFile { get; set; }
            public CopyFileTask(string sourceFile, string targetFile)
            {
                SourceFile = sourceFile;
                TargetFile = targetFile;
            }
        }

        private void Button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            backgroundWorker.CancelAsync();
        }

    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T22:20:15+00:00Added an answer on May 12, 2026 at 10:20 pm

    Have you looked at using Dispatcher.Invoke?

    Dispatcher.Invoke(new Action(() => { Button_Start.Content = i.ToString(); }));
    

    Or use BeginInvoke if you want something to happen asynchronously.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 222k
  • Answers 222k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Seeing as I don't see "clusterMS" listed in any of… May 13, 2026 at 12:22 am
  • Editorial Team
    Editorial Team added an answer You could use a non-visible literal controls in your list… May 13, 2026 at 12:22 am
  • Editorial Team
    Editorial Team added an answer Yes, that's correct. The implementation of the property will call… May 13, 2026 at 12:22 am

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I want use html5's new tag to play a wav file (currently only supported
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
In order to apply a triggered animation to all ToolTip s in my app,
I have a French site that I want to parse, but am running into

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.