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

  • SEARCH
  • Home
  • 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 7864611
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T23:50:11+00:00 2026-06-02T23:50:11+00:00

In MSDN article about BackgroundWorker.CancelAsync method, there is a caution which says: Be aware

  • 0

In MSDN article about BackgroundWorker.CancelAsync method, there is a caution which says:

Be aware that your code in the DoWork event handler may finish its
work as a cancellation request is being made, and your polling loop
may miss CancellationPending being set to true. In this case,
the Cancelled flag of
System.ComponentModel.RunWorkerCompletedEventArgs in your
RunWorkerCompleted event handler will not be set to true, even
though a cancellation request was made. This situation is called a
race condition and is a common concern in multithreaded programming.

What is the correct and good solution to avoid this race condition?

Here is my sample code, that provokes the apperance of this condition:

public partial class MainWindow : Window
{
    BackgroundWorker bW;
    int bWsCount = 0;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_MouseMove(object sender, MouseEventArgs e)
    {
        if (bW != null)
            bW.CancelAsync();
        bW = new BackgroundWorker();
        bW.WorkerSupportsCancellation = true;
        bW.DoWork += new DoWorkEventHandler(bW_DoWork);
        bW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bW_RunWorkerCompleted);
        bW.RunWorkerAsync(0);
        bWsCount++;
        labelBackgroundWorkersCount.Content = bWsCount;
    }

    void bW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        if (e.Cancelled || worker.CancellationPending)
        {
            bWsCount--;
            labelBackgroundWorkersCount.Content = bWsCount;
        }
        else
            worker.RunWorkerAsync(1000);
    }

    void bW_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        int sleepDuration = Convert.ToInt32(e.Argument);
        if (worker.CancellationPending) { e.Cancel = true; return; }
        Thread.Sleep(sleepDuration);
        if (worker.CancellationPending) { e.Cancel = true; return; }
    }
}
  • 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-06-02T23:50:13+00:00Added an answer on June 2, 2026 at 11:50 pm

    There is no way to avoid it, not every threading problem has a solution. These things can be reasoned out when you push them to the extreme. Imagine the code in your UI thread calls CancelAsync() a nanosecond before the worker thread completes. Just as the thread is executing its last machine code instruction. Clearly there’s no possible way this could be detected by the thread. Nor is there any possible way for the UI thread to see that the thread is on its last instruction.

    This is not a real problem, just keep it in mind when you write your RunWorkerCompleted event handler. If the e.Cancelled property is false then the worker completed anyway. If necessary, you can simply && it with another bool that you set to true when you call CancelAsync(). Roughly:

        private bool cancelRequested;
    
        private void CancelButton_Click(object sender, EventArgs e) {
            cancelRequested = true;
            backgroundWorker1.CancelAsync();
        }
    
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
            if (e.Error != null) throw e.Error;
            if (!e.Cancelled && !cancelRequested) {
                // Completed entirely normally
                //...
            }
        }
    

    Please do keep in mind that this not just a race in code. The far more practical problem is that this is a race in the user’s brain as well. With the failure mode that everything completes normally a millisecond before the user clicks the Cancel button.

    So as far as the user knows, the operation was canceled when in fact it was not. This can have unpleasant consequences, ones you’ll have to deal with by telling the user what really happened. In which case it really doesn’t make any sense to use the code snippet, it will work just as well if you only cancel the operation and allow it to complete anyway.

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

Sidebar

Related Questions

I've read the MSDN article about the layouts pass, that states: When a node
This MSDN article stated that: processors are free to reorder this code internal static
There is this MSDN article about spcial characters in WPF/XAML : But those Things
I have been reading an article about Lockless Programming in MSDN. It says :
I was reading the MSDN article about how to implement IDisposable and I am
I read the msdn article about disposing objects in http://msdn.microsoft.com/en-us/library/ee557362(office.14).aspx now I'm really confused
I was reading an article on MSDN Magazine about using the Enumerable class in
From the MSDN article on STAThread: Indicates that the COM threading model for an
I've found this MSDN article that explains how to monitor processes and services with
As per this MSDN article: W3C Extended Log File Format (IIS 6.0) It says

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.