Home > other >  Using global bool as a terminator for async functions
Using global bool as a terminator for async functions

Time:07-26

I'm currently writing code to automate functions in Excel using c#. Each c# form button is asynchronous and performs a different task in Excel, but Excel doesn't allow multiple actions in one sheet at the same time.

How can I achieve a way for the button to wait for another function to finish its task?

My idea was to use a global bool value (excelBeingAutomated) that works as a terminator - when one function finishes, it sets the excelBeingAutomated to false, so the next function can set it to true and do its function and so on.

ANY idea is highly appreciated.

CodePudding user response:

Don't try to use a boolean or any other global field for synchronization, writing and reading variables from different threads is not safe. So you would need a lock or a ManualResetEvent or something similar.

My recommended way would be to use a dialog to block user input until the task has completed. I.e.

  1. start your task
  2. create a form/window
  3. register a callback on the task to close the form on the main thread
  4. show the form using ShowDialog

This assumes you are using Tasks to describe your asynchronous operations. This will prevent the user from doing anything else while the operation is processing, and that is typically what you would want to do. All of this can be done as a static method, so you could write something like var result = ProgressDialog.Run("Please Wait", MyMethodToRunInTheBackground).

The alternative would be to have a queue. I.e. put your task on a queue, and use a single thread to process the tasks, or use a limitedconcurrencyTaskScheduler that does the same thing. But if you do this you probably want to show the queue to the user in some visual way, and ideally allow tasks to be removed from the queue. Otherwise there is a risk nothing happens when the user press a button, so he starts pressing other buttons randomly, and after 10 seconds everything happens at once.

  • Related