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 7568201
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T14:51:49+00:00 2026-05-30T14:51:49+00:00

I’ve got a class which abstracts performing long running methods on a background thread

  • 0

I’ve got a class which abstracts performing long running methods on a background thread away from my WPF MVVM view models. I also have this class interfaced and IoC injected into most of my view models.

public interface IAsyncActionManager : INotifyPropertyChanged
{        
    /// <summary>
    /// Sets and gets the IsBusy property.
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary>
    bool IsBusy { get; }

    Task StartAsyncTask(Action backgroundAction);
 }

My view models use this class in various ways such as:

private void LoadStuff()
{
    ActionManager.StartAsyncTask(() => { // Load stuff from database here });
}

And in some of my XAML I bind directly to the IsBusy property:

<Grid Cursor="{Binding ActionManager.IsBusy, Converter={Converters:BusyMouseConverter}}">

Anyway – now you have the background, I’m now trying to do something a little more fancy:

private Task _saveChangesTask;
public void SaveChanges()
{
    if (_saveChangesTask != null && _saveChangesTask.Status != TaskStatus.Running)
        return;

    _saveChangesTask = ActionManager.StartAsyncTask(() =>
    { 
        // Save stuff here - slowly
    });
}

This is simplified as I’ve also got it hooked up via a Command object which WPF uses in its view with CanExecute etc but this ‘caching’ of the task is so that the save action doesn’t get run twice.

Now, getting to the problem, I want to unit test this logic – how do I do so?
I’ve tried using a TaskCompletionSource in my test but I cannot get my Task into a ‘Running’ state…?

var tcs = new TaskCompletionSource<object>();
// tcs.Task.Status is now WaitingForActivation

// tcs.Task.Start(Synchronous.TaskScheduler); // Doesn't work - throws an Exception.

A.CallTo(() => mockAsyncActionManager.StartAsyncTask(A<Action>._, A<Action<Task>>._)).Returns(tcs.Task);

Anyone got any clues? Can I do this?

I’ve got an idea that I’m using the TPL wrongly – that I shouldn’t be relying on task Status – but not sure how to achieve a similar thing in another way (suggestions welcome).

Cheers,

  • 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-30T14:51:51+00:00Added an answer on May 30, 2026 at 2:51 pm

    I believe the problem here does lie (as you said) with the check of the Status property.

    The TaskStatus enumeration indicates that a Task instance doesn’t just have a binary state of running/not running, but rather, can be in a number of states.

    When a Task is created, depending on the TaskScheduler, it will put the Task in the following states before the Running state:

    • Created – The task has been initialized but has not yet been scheduled.
    • WaitingForActivation – The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.
    • WaitingToRun – The task has been scheduled for execution but has not yet begun executing.

    With that, your check against the TaskStatus of Running can fail because it is in one of the above states.

    What I’d recommend is you simply check against the reference for the Task; if it’s null, then create a new Task, otherwise, just return.

    The assumption here is that the call to SaveChanges is meant to be called once on the object (or not do anything until a save is complete).

    If you are going to call the method again (presumably, because other changes have been made), you should have a continuation on the Task that will set the reference to the Task to null when the operation is complete. This way, the check against the reference will succeed when SaveChanges is called a second time.

    On a side note, I’ve pointed out in the comments that you have a race condition. If you are going to set the reference to the Task back to null in the continuation, then you’ll need to perform the check and the assignment in a thread-safe way (since the continuation will run on another thread), like so:

    private Task _saveChangesTask;
    
    // Used to synchronize access to _saveChangesTask
    private readonly object _saveChangesTaskLock = new object();
    
    public void SaveChanges()
    {
        // Guard access to the reference.
        lock (_saveChangesTaskLock)
        {
            // Check and assign.
           if (_saveChangesTask != null) return;
    
            _saveChangesTask = ActionManager.StartAsyncTask(() =>
            { 
                // Save stuff here - slowly
    
                // Done saving stuff here - slowly
                // (BTW, is the above a reference from "True Lies"?)
                // Remove reference to task.  This is on another thread
                // so using a lock again is ok.
                // Guard access to the reference.
                lock (_saveChangesTaskLock) _saveChangesTask = null;
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am currently running into a problem where an element is coming back from
I have a text area in my form which accepts all possible characters from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

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.