Question

I have a background async Task that is fired from a button click. I have an IsBusy property that is updated when the Task starts and within a finally block to account for cancellation or completion.

Currently my button click event cancels the previous Task and starts a new Task when it is re-clicked; however since the cancellation of the first Task may linger past the start of the new one, a boolean IsBusy indicator can become out of sync.

My issue is how to deal with this situation.

My current solution is not to update the boolean value directly but to use an integer that is incremented / decremented on start and completion - with the IsBusy property returning BusyCount > 0. This however requires additions for thread safety, and does not feel like a good solution.

Another thought was to store the Task when it is fired and only start the new task as a continuation of the first. This accounts for the cancellation issue, but forces a unnecessary delay (however fractional) and a 'contract' for the caller rather than the task.

My final thought was to create something like a BusyTokenSource class that hands out disposable BusyTokens that get added / removed from a thread-safe collection.. but this seems like overkill.

Is there a better/proper/common way to handle this type of situation?

Edit:

I ended up going with my last thought above, and wrote the 'BusyToken' classes. This way I can simply wrap a function in a using(BusyTokenSource.GetToken()){} and let the internal collection and Dispose take care of the counting and busy status.

Was it helpful?

Solution

I think you should have one busy-status per Task. Not sure how your BusyTokenSource idea works but it sounds a little like it.

Create a holder class:

class BusyStatus { bool IsBusy; }

And give a new instance of it to each Task you start. When you are no longer interested in the old task, just discard the old BusyStatus and create a new instance. The old Task will eventually finish and set the busy status, but on the old instance which nobody uses anymore.

Just make sure that the old task does not accidentally reference the new BusyStatus instance.

As a more general rule it is often useful to have each Task (or Thread) work on distinct data structures. This a useful general guiding principle. It gains you simplicity and makes it easy to achieve safety.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top