Cancelling a background worker without worker.CancellationPending check? - c#

I have a Validator class which has a Validate function, This validate function loops over bunch of file and validates them. User can cancel the validate process.
For cancelling the back ground worker I need ta reference of the background worker instance in Validtor class (for cancelling the validation process) and call CancellationPending on it.
But the problem is Validator class can't have reference to background worker because there are times when we call the "Validate" function synchronously and Validator class does not have to know this.
So far I have tried replacing backgroundworker.CancellationPending check with some flag e.g. IsCanceled which do not seems to work.

You have two options:
Make two overloads of the Validate method. One that is synchronous and one that is asynchronous and cancellable.
Change your Validate method so that the calling code is responsible for looping over the files (consider an iterator method, using yield)
I'd go with option 1 as it is a smaller change.

Related

BackgroundWorker problems on exit

I am having a bit of a conundrum here, and would like to know a couple of things:
Am i doing this wrong?
What is the expected behaviour of a backgroundworker in different scenarios...
If possible, get an answer as to why i am getting specific behaviour would be nice...
For point 1, and ultimately 3 as well, i will explain what i am doing in Pseudo-Code so that you have the details without actually spitting out thousands of lines of code. While i write this post, i will look at the code itself to ensure that the information is accurate as far as when and what is happening. At the very end, i will also detail what is happening and why i am having issues.
Pseudo-Code details:
I have a main UI thread (WinForms form), where after selecting a few configuration options you click a button.
This button's event does some preliminary setup work in memory and on the file system to get things going and once that's done fires off ONE backgroundworker. This backgroundworker initializes 5 other backgroundworkers (form scope variables), sets their "Done" flags (bool - same scope) to true, sets their "Log" vars to a new List<LogEntry> (same scope) and once that's done calls a method called CheckEndConditions. This method call is done within the DoWork() of the initial backgroundworker, and not in the RunWorkerCompleted event.
The CheckEndConditions method does the following logic:
IF ALL "Done" vars are set to True...
Grab the "Log" vars for all 5 BWs and adds their content to a master log.
Reset the "Log" vars for all 5 BWs to a new List<LogEntry>
Reset the "Done" vars for all 5 BWs to False.
Call MoveToNextStep() method which returns an Enum value representative of the next step to perform
Based on the result of (5), grab a List<ActionFileAction> that needs to be processed
Check to ensure (6) has actions to perform
If NO, set ALL "Done" flags to true, and call itself to move to the next step...
If YES, partition this list of actions into 5 lists and place them in an array of List<ActionFileAction> called ThreadActionSets[]
Check EACH partitioned list for content, and if none, sets the "Done" flag for the respective thread to true (this ensures there are no "end race scenarios")
Fire off all 5 threads using RunWorkerAsync() (unless we are at the Finished step of course)
Return
Each BW has the exact same DoWork() code, which basically boils down to the following:
Do i have any actions to perform?
If NO, set my e.Result var to an empty list of log entries and exit.
If YES, loop for each action in the set and perform 4-5-6 below...
What context of action am i doing? (Groups, Modules, etc)
Based on (4), what type of action am i doing? (Add, Delete, Modify)
Based on (5), perform the right action and log everything you do locally
When all actions are done, set my e.Result var to the "log of everything i've done", and exit.
Each BW has the same RunWorkerCompleted() code, which basically boils down to the following:
TRY
From the e.Result var, grab the List<LogEntry> and put it in my respective thread's "Log" var.
Set my respective "Done" var to true
Call CheckEndConditions()
CATCH
Set my respective "Done" var to true
Call CheckEndConditions()
So that is basically it... in summary, i am splitting a huge amount of actions into 5 partitions, and sending those off to 5 threads to perform them at a faster rate than on a single thread.
The Problem
The problem i am having is that i often find myself, regardless of how much thought i put into this for race scenarios (specifically end ones), with a jammed/non-responsive program.
In the beginning, i had setup my code inefficiently and the problem was with End Race Scenarios and the threads would complete so fast that the last call made to CheckEndConditions saw one of the "Done" vars still set to false, when in fact it wasn't/it had completed... So i changed my code to what you see above which, i thought, would fix the problem, but it hasn't. The whole process still jams/falls asleep, and no threads are actually running any processing when this happens which means that something went wrong (i think, not sure) with the last call to CheckEndConditions.
So my 1st question: Am i doing this wrong? What is the standard way of doing what it is i want to do? The logic of what i've done feels sound to me, but it doesn't behave how i expect it to so maybe the logic isn't sound? ...
2nd question: What is the expected behaviour of a BW, when this scenario occurs:
An error occurred within the DoWork() method that was un-caught... does it fire off the RunWorkerCompleted() event? If not, what happens?
3rd question: Does anyone see something obvious as to why my problem is occurring?
Thanks for the help!
Reposting my comment as answer per OP's request:
The RunWorkerCompleted event will not necessarily be raised on the same thread that it was created on (unless it is created on UI thread) See BackgroundWorker RunWorkerCompleted Event
See OP comments for more details.

Returning status from a worker class

I have a service class and a worker class. The worker class does all the processing.
class WorkerClass
{
public void ProcessWork(<params to the method>)
{
// Get the tasks from the DB.
// Call a 3rd party web service to process each of the tasks.
}
}
In my service class, I instantiate the worker class and call the method. The question is, how do I get the number of tasks processed in the service class?
I have thought of 3 options:
Expose an event from the worker class. Hook up an event handler in the service class.
Modify the signature of ProcessWork method so that it accepts a delegate:
public void ProcessWork(object obj1, Action<int, int> actionProgressTracker)
Expose a property from the worker class and get the property in the service class. Refresh the property every 30 seconds.
What would be a clean way of getting the status?
The first two options are really functionally identical. Both can work just fine for what you need to do. The second has an implication that the delegate is required, whereas the first implies that it is not. An event might also imply that it is used beyond the scope of just this one method.
As for the third option, it doesn't give the caller the opportunity to execute code when the number updates, it just gives them the opportunity to access the information.
So if the caller of this type is going to need to do something with this information *every time the value changes) then you should be using something comparable to one of the first two options so that the worker can "push" information to the caller.
If the caller wants to "pull" the information from the worker whenever it wants the information, then go with the third option.
Note that there is also a Progress class that you can use, with a corresponding IProgress interface, that's comparable to your first two options, but is specifically tailored for a worker updating a UI with progress.
Both push and pull methods can actually be sensible for updating a UI with progress of a backround task. If progress occurs infrequently it may make sense to update the UI every time progress changes, so the UI will want to be "notified" of when those updates happen. If the updates are very frequent, then the UI may want to instead have a timer and pull the current status every so often, to avoid taxing the UI with more updates than are needed or than it can handle.
Of course, if you're pushing information and not just something like a percent complete, then it may be important to not lose any of that information, in which case your 3rd approach isn't an option, as multiple updates may happen in between fetches.
And of course if you're writing a sufficiently generalized worker, you may want to expose both a push and pull mechanism, to let the caller choose the appropriate one.

Automatic Invoking for cross-thread actions

is there any solution for this scenario:
I do some time-consuming things on a new Thread (using Tasks). In this thread I want to update UI elements (text) so that the user knows what happens. This should happen at real-time, not only when a Task finished.
I always must explicitly call Dispatcher.Invoke() (it's the UI-Thread dispatcher) if I want to change something. Is there a way to run something asynchronously without having to invoke explicitly? I found a solution using the TaskFactory and specifying a TaskScheduler. But this locks the UI when UI-calls are made.
Is there a way to do this, without locking the UI?
EDIT: Because of some slight misunderstandings this edit.
I want that once I call something like
uiControl.Text = "Test 123";
on the worker-thread to be automatically invoked on the UI-Thread if needed. So in this case it's needed, but I want to get rid of all these Invoke-calls. So if there is a nifty solution it would be great. Otherwise I have to use explicit invokes, not nice but ok.
PostSharp has this implemented as a method level aspect. What it means in terms of implementation is that you decorate a method with [DispatchedMethod] attribute and it will be dispatched to the UI thread every time it is called (by any thread). Take a look here for more details:
http://www.postsharp.net/aspects/examples/multithreading
http://www.postsharp.net/threading/thread-dispatching
http://doc.postsharp.net/##T_PostSharp_Patterns_Threading_DispatchedAttribute
You can do the operation on main thread and just call Application.DoEvents() from time to time in order to process UI events ...
Note that this only works for winforms so probably not a correct answer.
HighCore suggested this as a better answer https://stackoverflow.com/a/21884638/643085

Need second (and third) opinions on my fix for this Winforms race condition

There are a hundred examples in blogs, etc. on how to implement a background worker that logs or gives status to a foreground GUI element. Most of them include an approach to handle the race condition that exists between spawning the worker thread, and creating the foreground dialog with ShowDialog(). However, it occured to me that a simple approach is to force the creation of the handle in the form constructor, so that the thread won't be able to trigger an Invoke/BeginInvoke call on the form prior to its handle creation.
Consider a simple example of a Logger class that uses a background worker thread to log to the foreground.
Assume, also, that we don't want NLog or some other heavy framework to do something so simple and lightweight.
My logger window is opened with ShowDialog() by the foreground thread, but only after the background "worker" thread is started. The worker thread calls logger.Log() which itself uses logForm.BeginInvoke() to update the log control correctly on the foreground thread.
public override void Log(string s)
{
form.BeginInvoke(logDelegate, s);
}
Where logDelegate is just a simple wrapper around "form.Log()" or some other code that may update a progress bar.
The problem lies in the race condition that exists; when the background worker thread starts logging before the foreground ShowDialog() is called the form's Handle hasn't yet been created so the BeginInvoke() call fails.
I'm familiar with the various approaches, including using a Form OnLoad event and a timer to create the worker task suspended until the OnLoad event generates a timer message that starts the task once the form is shown, or, as mentioned, using a queue for the messages. However, I think that simply forcing the dialog's handle to create early (in the constructor) ensures there is no race condition, assuming the thread is spawned off by the same thread that creates the dialog.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle(v=vs.71).aspx
MSDN says: "If the handle has not yet been created, referencing this property will force the handle to be created."
So my logger wraps a form, and its constructor does:
public SimpleProgressDialog() {
var h = form.Handle; // dereference the handle
}
The solution seems too simple to be correct. I'm specifically interested in why the seemingly too simple solution is or isn't safe to use.
Any comments? Am I missing something else?
EDIT: I'm NOT asking for alternatives. Not asking how to use NLog or Log4net, etc. if I were, I'd write a page about all of the customer constraints on this app, etc.
By the number of upvotes, there are a lot of other people that would like to know the answer too.
If you are concerned that referencing Control.Handle relies on a side effect in order to create the handle, you can simply call Control.CreateControl() to create it. However, referencing the property has the benefit of not initializing it if it already exists.
As for whether this is safe or not assuming the handle is created, you are correct: as long as you create the handle before spawning the background task on the same thread, you will avoid a race condition.
My two cents: there's no real need to force early handle creation if the logging framework simply maintains a buffer of undisplayed log entries while the handle has not been created. It could be implemented as a Queue, or many other things. Messing with the order of handle creation in .NET makes me squeamish.
I think the only danger is decreased performance. Handle creation is deferred in winforms to speed things up. However, since it sound like this is a one-time operation, it doesn't sound costly, so I think your approach is fine.
You can always check the IsHandleCreated property of your form to see if the handle has been built yet; however, there are some caveats. I've been in a similar spot to yours, where winforms controls are being created/destroyed dynamically with lots of multithreading going on. The pattern we wound up using was quite a bit like this:
private void SomeEventHandler(object sender, EventArgs e) // called from a bg thread
{
MethodInvoker ivk = delegate
{
if(this.IsDisposed)
return; // bail out! Run away!
// maybe look for queued stuff if it exists?
// the code to run on the UI thread
};
if(this.IsDisposed)
return; // run away! killer rabbits with pointy teeth!
if(!this.IsHandleCreated) // handle not built yet, do something in the meantime
DoSomethingToQueueTheCall(ivk);
else
this.BeginInvoke(ivk);
}
The big lesson here is to expect a kaboom if you attempt to interact with your form after it has been disposed. Don't rely on InvokeRequired, since it will return false on any thread if the control's handle hasn't been created yet. Also don't rely solely on IsHandleCreated since that will return false after the control has been disposed.
Basically, you have three flags whose state will tell you what you need to know about the control's initialization state and whether or not you're on a BG thread relative to the control.
The control can be in one of three initialization states:
Uninitialized, no handle created yet
InvokeRequired returns false on every thread
IsHandleCreated returns false
IsDisposed returns false
Initialized, ready, active
InvokeRequired does what the docs say
IsHandleCreated returns true
IsDisposed returns false
Disposed
InvokeRequired returns false on every thread
IsHandleCreated returns false
IsDisposed returns true
Hope this helps.
Since you do create the window on the calling thread you can end up with deadlocks. If the thread that creates the window has no message pump running your BeginInvoke will add your delegate call to the message queue which will never be emptied, if you do not have an Application.Run() on the same thread which will process the window messages.
It is also very slow to send around window messages for each log message. It is much better to have a producer consumer model where your logging thread adds a message to a Queue<string> which is emptied by another thread. The only time you need to lock is when you enqueue or dequeue a message. The consumer thread can wait for an event with a timeout to start processing the next message when either the event was signaled or the timeout (e.g. 100ms) has elapsed.
A thread safe blocking Queue can be found here.

how to implement a step-by-step button in c#?

I implemented an algorithm in c# and I want to make a gui for it, in my gui i want to put a button that with any click the gui shows a step forward in algorithm, so i think i need to put something like pause? statements in my code that with any click it can resume. how should i do that? or is there any other suggestion for implementing this idea?
It sounds like really you need to turn your algorithm into a state machine - instead of actively "pausing" it, you would actively "advance" it.
You may find iterator blocks useful... if your algorithm is pretty much in one method at the moment, you may be able to change it to insert a yield return statement at the end of each logical step, returning some indication of the current status.
That's not an entirely normal use of iterator blocks, but it could be the simplest way forward here. Your UI would call GetEnumerator once at the start, and then MoveNext() each time the button is clicked (followed by accessing the Current property to get at the current state). Don't forget to dispose of the iterator when you've finished with it.
Run your algorithm in a thread different than your UI thread.
For synchronization, create some kind of wait handle, e.g. an AutoResetEvent.
The "pause" statement you are looking for is myWaitHandle.WaitOne() (called by your algorithm thread).
Allow the algorithm to continue by executing myWaitHandle.Set() in your UI thread.
This method has the advantage that your user interface stays responsive while a step of your algorithm is being executed.
You have to decide what is a "step" in your algorithm. Then you need to rewrite your algorithm and wrap it in a class with the following interface:
interface ISteppedAlgorithm
{
bool NextStep(); //returns if the algorithm is finished
IStepResult LastStepResult {get;}
}
and now your GUI will drive the algorithm prepared in this way. After you press the button, the NextStep() method will be invoked. If it returns false disable the button (or indicate in whatever other way that its all done). Then read the LastStepResults and update the display.h
From your description I think you want a "wizard" that is basically an application with previous / next buttons.
http://www.differentpla.net/content/2005/02/implementing-wizard-c
However If you just have a long running task and want to have some breaks in it, there are different ways to solve it.
Sperate you task in multiple methods.
After a method is completed, wait until the user hit's next.
Let the task run in it's own thread and at a point where it should wait let the thread sleep until you set a specific var:
LongRunningMethod1();
while(continue1 == true)
{
Thread.Sleep(50);
}
LongRunningMethod2()
while(continue2 == true)
{
Thread.Sleep(50);
}
Set continue1 and 2 to true in your main thread to let the background thread do his work.
If it's just to "observe" the state of the algorithm as it develops, why not add some events (probably just one at the end) and let the event handler store an array of the states. The UI can simply iterate forward\backwards over this as and when needed.

Categories

Resources