Best practice for multiple long-methods using backgroundworker - c#

I have a form that has many long-methods. My quest is: What is the best practice? Use anonymous method and only one backgroundworker or create an instance of BackgroundWorker to each long-method.
Please help. Thanks.

I would personnaly use one instance of BackgroundWorker for each of your tasks. However, keep in mind that you may call several times the same delegate method in multiple different instances of thread.
By having one BackgroundWorker per long-method task, you will have plenty control over your methods. Furthermore, as far as my understanding goes, once an instance of a BackgroundWorker performs a task, it is busy with this background task and therefore making it unavailable for others. I may perhaps be mistaken though, but that is anyway the way I would do it, as your DoWork() event handler can do only what it is asked to do for this BackgroundWorker. So, it seems impossible to me to perform totally different tasks for only one instance of BackgroundWorker.
Does this help?

In summary:
Advantages in one BackgroundWorker:
You control the order of the execution for the multiple method. However, this is also a disadvantage, because if you use multiple BackgroundWorkers, you "assume" they are executed parallely and not have to worry about the order;
Less overhead for thread creation and disposal (if possible, use same instance every time, but that's not always possible, depending on what starts the process. It's not possible if you want it to be done concurrently);
If you want to communicate between thread, you can accumulate a batch communication and do it more efficiently. Moreover, it may save you some of that communication if all methods are run in the same thread.
Advantages in multiple BackgroundWorkers:
The aforementioned parallelism;
Each end-of-process can use another delegate and therefore do some other operation.
Hope it helps!

Related

Writing a class in an asynchronous way or just calling it asynchronously

I want to create a class that represents a long running operation.
This class:
Should be constructed with some parameters,
It should run the operation by calling a method,
It should report its progress and it should report the end of the operation.
I have used BackgroundWorker before but I don't have any direct experience with Threads or Tasks, and I need to use .NET 3.5 so no async-await.
One way to do it is to couple the class with a BackgroundWorker. So the user will pass a BackgroundWorker to the class and the class will raise that BackgroundWorkers events. But I'm not sure if it would be good design.
The other way is to create the class, so that it will have its own events for progress change, progress end, and so on. The BackgroundWorker will be in the so called bootstrapper, and the BackgroundWorkers events will be connected to the class' events. But this seems like an unnecessary level of abstraction.
What is the usual way of designing these kinds of classes. Is it better to write it as a sort of asynchronous class, or is it better to write it in a normal way and just call it asynchronously?
Summary: In the comments, MikeCorcoran summarized the question beautifully; I am wondering "whether to write the class so it automatically does its work asynchronously within each method, or write the class so it works synchronously but is designed to be run on a background thread."
The answer is, "it depends."
If there's nothing in the code that requires it to use multiple threads or to operate asynchronously, then you should write it as a normal method (or class). That way, you can test it synchronously, or even use it synchronously in simple programs. That you elect to call it from a BackgroundWorker or a Task or some other way shouldn't matter.
Always do things in the simplest way you can, and still meet the design goals. If what the class does isn't inherently asynchronous, then don't force it to be.

Proper way of executing method in regular interval

I want to execute the certain method of a class in regular interval when certain method is executed. C# has three methods I can use to furnish my needs. Since I am new to C# programming, I am confused in selecting the right method. Based on my study, the three classes are:
System.Windows.Forms.Timer
Systems.Timer
System.Diagnostics.StopWatch
My requirement is fairly simple: Execute the certain method at regular interval when the certain method is called.
Please suggest the situation where one is more preferred over others.
StopWatch is for measuring time, not for scheduling events, so let's rule that one out.
System.Windows.Forms.Timer is based on Windows Forms and requires the Windows message loop to run. Is your project Windows Forms, then you can use this. If not, do not use it (it won't work).
System.Timers.Timer is a general purpose timer. I would use this; it should work in all scenarios, you don't have to worry about the message loop running. You can also make this Timer synchronize automatically using it's SynchronizationObject property.
Finally, there is a System.Threading.Timer, which is not thread safe out of the box (meaning your method will get called on a worker thread, so if you need synchronization or dispatch on a specific thread due to UI, you will need to handle that yourself).
There are many subtle differences to these timers, I'd recommend you read the article Comparing the Timer Classes on MSDN for the full story.
Without knowing your specific use case, we can't tell you which is best. But in general:
System.Windows.Forms.Timer - Will call your function on the UI thread each time. Use this if you are planning to access UI controls during the event.
System.Timers.Timer - Will call your function on a worker thread. Use this in a context that is not Windows Forms or where you don't need to access any UI elements
System.Diagnostics.StopWatch - this is for timing how long things take. It won't help you here.
See: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

Isn't blindly using InvokeRequired just bad practice?

I am a novice programmer so I could be completely mistaken here, but this issue bugs me more then it should.
This is actually a follow-up from this question.
The accepted answer was, that you have to call InvokeRequired in order to avoid some overhead, because there is a chance you are already operating on the UI thread.
In theory, I agree that it could save some time. After some tests I found out that using Invoke takes about twice the time compared to calling an operation normally (tests like setting the text of a label n times, or placing a very, very big string in a RichTextBox).
But! Then there is practice.
MSDN documentation says:
This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.
In most cases, you do know when you try to access a control from another thread. Actually the only situation I can think of is, when the control is accessed from a method that can be called by thread X aswell as the owner thread. And that to me is a very unlikely situation.
And even if you genuinely don't know which thread tries to manipulate the control, there is the fact that the UI thread doesn't have to be updated that frequently. Anything between 25-30 fps should be okay for your GUI. And most of the changes made in the UI-controls takes far less then milliseconds to perform.
So if I understand corrrectly, the only scenario where you have to check if an invoke is required is when you don't know which thread is accessing the control and when the GUI update takes more than about 40 ms to finish.
Then there is the answer to this question I asked on http://programmers.stackexchange.com. Which states that you shouldn't be busy with premature optimisation when you don't need it. Especially if it sacrifices code readability.
So this brings me to my question: shouldn't you just use invoke when you know a different thread accesses a control, and only when you know your UI thread can access that piece of code and you find that it should run faster, that you should check if an Invoke is required?
PS: after proofreading my question it really sounds like I am ranting. But actually I am just curious why InvokeRequired is seemingly overused by many more-experienced-than-me programmers.
You are taking things out of context here. The first question you linked linked another question which specifically was about writing a thread-safe method to access a UI control.
If you don't need a thread-safe access to a UI control, because you know you won't update it from another thread, then certainly, you shouldn't employ this technique. Simply update your UI control without using InvokeRequired or Invoke.
On the other hand, if the call will always originate in a thread other than the UI thread, simply use Invoke without first checking for InvokeRequired.
This leads to three simple rules:
If you update the control only from the UI thread, use neither InvokeRequired nor Invoke
If you update the control only from a thread other than the UI thread, use only Invoke.
If you update the control from both the UI thread and other threads, use Invoke in combination with InvokeRequired.
In practice people tend to call the same method from both the foreign and the owning thread. The usual pattern is that the method itself determines whether the thread is the owning thread. If it is, it executes the follow-up code. If it isn't the method calls its own self using Invoke this time.
One benefit of this is that it makes the code more compact, as you have one method related to the operation instead of two.
Another and probably more important benefit is that it reduces the chance that the cross thread exception will be raised. If both methods were available at any time and both threads could choose any of the two, then there would be a chance of a seemingly legitimate method call raising an exception. On the other hand, if there's only one method that adapts to the situation, it provides a safer interface.

.NET threading solution for long queries

Senerio
We have a C# .Net Web Application that records incidents. An external database needs to be queried when an incident is approved by a supervisor. The queries to this external database are sometimes taking a while to run. This lag is experienced through the browser.
Possible Solution
I want to use threading to eliminate the simulated hang to the browser. I have used the Thread class before and heard about ThreadPool. But, I just found BackgroundWorker in this post.
MSDN states:
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.
Is BackgroundWorker the way to go when handling long running queries?
What happens when 2 or more BackgroundWorker processes are ran simultaneously? Is it handled like a pool?
Yes, BackgroundWorker can significantly simplify your threading code for long-running operations. The key is registering for the DoWork, ProgressChanged, and RunWorkerCompleted events. These help you avoid having to have a bunch of synchronization objects passed back and forth with the thread to try to determine the progress of the operation.
Also, I believe the progress events are called on the UI thread, avoiding the need for calls to Control.Invoke to update your UI.
To answer your last question, yes, threads are allocated from the .NET thread pool, so you while you may instantiate as many BackgroundWorker objects as you'd like, you can only run as many concurrent operations as the thread pool will allow.
If you're using .NET 4 (or can use the TPL backport from the Rx Framework), then one nice option is to use a Task created with the LongRunning hint.
This provides many options difficult to accomplish via the ThreadPool or BackgroundWorker, including allowing for continuations to be specified at creation time, as well as allowing for clean cancellation and exception/error handling.
I had ran in similar situation with long running queries. I used the asynchronous invoke provided by delegates. You can use the BeginInvoke method of the delegate.
BackgroundWrokerks are just like any other threads, accept they can be killed or quit, w/out exiting the main thread and your application.
ThreadPool uses a pool of BackgroundWorkers. It is the preferred way of most multi threading scenarios because .net manages threads for you, and it re-uses them instead of creating new ones as needed which is a expensive process.
Such threading scenarios are great for processor intensive code.
For something like a query which happens externally, you also have the option of asynchronous data access. You can hand off the query request, and give it the name of your callback method, which will be called when query is finished and than do something with the result (i.e. update UI status or display returned data)..
.Net has inbuilt support for asynchronous data querying
http://www.devx.com/dotnet/Article/26747

C#: How can i elegantly and or simplistically make cross threaded calls?

i have a tcp server that, when a client connects, it makes a new thread and adds them to it but everytime i try to access information about the connection or anything about it, say even keeping a count of how many clients are connected, i get a cross-thread illegal exception or something like that.
ive read several tutorials on things called delegates, invoking and reflection but all the examples or tutorials simply confuse me as doing one invoke a certain way fails in another.
is there an elegant or simplistic way of doing this? do i need to learn how to do something else first? or am i just making things way more complex than they are? any suggestions, links or tips are most appreciated and accepted.
I suppose you go directly to the UI from your client connection thread. This is not good. Instead, consider using some variation of MVP pattern to decouple presentation logic from views. Thus, your "connection threads" will talk to some intermediary, presenters will talk to the same intermediary and just hand off some data for view to display.
As far as cross-thread operations are concerned, particulary UI thread operations, I find SynchronizationContext to be very useful in cicrumstances when you want to marshal a call from a non-UI thread to the UI thread. See this article for more in-depth discussion.
I guess you get this cross thread exception since you are trying to update screen elements from your threaded code. If you need to do that you can get a simple solution using anonymous method.
Say that you want to add an item to a listbox called ListBoxLog. This code would do the trick from any thread:
ListBoxLog.Invoke((MethodInvoker)delegate { ListBoxLog.Items.Add("Done"); });
There's also a property to check .InvokeRequired you can check to see if invocation is nessecary. You would typically check that property in a function that could be called by both the main UI thread and any background thread.
You can also use BeginInvoke like I did with Invoke. BeginInvoke is totaly asynchronous and does not wait for the code in the delegate to finish.
Using delegates and events.
That would be my best answer.
http://www.codeproject.com/KB/cs/Cross_thread_Events.aspx
There are plenty of examples online to help you:
http://www.google.com/search?q=tcp+server+multi+thread
When using C#, the Concurrency and Coordination Runtime (CCR) also has a sample about implementing multithreaded tcp server. The CCR allows a much better paradigm to implement parrallel processing, it simplifies a lot of the standard multi-threading code.

Categories