SwingWorker vs BackgroundWorker - c#

In C# I came across Backgroundworker component for concurrency. Although it was slightly advanced than using a plain vanila thread, I found it to be much smoother.
I have not used SwingWorker in Java yet. While doing some coding on threads I came across this reference from JavaDoc for SwingWorker as a solution for threadsafety when working with swing objects.
Question: In C# I don't recall a statement like "not threadsafe for WinForm/WPF layouts, so use BackgroundWorker". I want to know if SwingWorker can be a substitute for threads in all aspect in Java, like how BackgroundWorker is used in C#?
For a novice, should I expect same performance/smooth running/full debug support for SwingWorker?

I want to know if SwingWorker can be a substitute for threads in all aspect in Java, like how BackgroundWorker is used in C#?
While a SwingWorker, which implements Runnable, Future and RunnableFuture, can be used anywhere a Runnable or Future is used, no, I wouldn't do this. A SwingWorker is a bit more complex to set up and use vs. a basic Thread/Runnable, and you would have no benefit to using it in non-Swing situations. The SwingWorker has been built to allow for creation of background threads while at the same time ensuring that certain portions of its code is called on the Swing event thread. When run in an application without a Swing event thread, this has no meaning.
Edit
You state:
That means a proper Swing based application has a combination of SwingWorker and basic Thread/Runnable for it to run smooth.
Where do you derive this from my statements above. Your statement doesn't make sense and is certainly not what I have stated above.
That's just useless and the reason I paid more attention - because it was directed by JavaDoc with the basis "Swing isn't threadsafe".
Which is also true of most all GUI libraries.

Related

Is using a ton of InvokeRequired methods cost effective?

I created a question topic here: Thread error in C# Windows Form
It seems that for everything that is involved with the threading timer must use InvokeRequired methods. So, I got a bunch of things that need this. Is using this a lot going to use up a lot of computer resources?
Is using this a lot going to use up a lot of computer resources?
It doesn't necessarily use up "computer resources", but using Control.Invoke and Control.BeginInvoke does have overhead.
One good option, in many situations, is to try to batch your calls which require Control.Invoke/BeginInvoke, which attempts to minimize the number of marshaling operations.

"Synchronous" functions in C#?

I am creating a custom statemachine and in order to be determinist, I have to "synchronise" my transitions. I'm not sure about the word "synchronize" but what I want is that when I call a function (through EventHandler), the system is like frozen before I can call another function (through EventHandler too).
It's kinda hard to explain it precisely in english but I think you know what I mean...
I was thinking about Threading but I'd REALLY like to avoid this...
If you are looking to emulate the effect of the "synchronized" keyword from java, the best way is probably to wrap the entire method code inside
lock(this)
{
// code
}
Not sure if that's what you are looking for, but C# iterator blocks are essentially state machines.
Synchronization is when you're in a multi-threaded environment and you need to make access to resources by the threads synchronized (1 at a time). This ensures unpredictable results are not achieved when threads are changing resources while other threads are trying to access them. There are many constructs available to you in C# to handle synchronization. It all depends on what your threads are trying to accomplish.
Here is a link from MSDN that shows some simple examples: http://msdn.microsoft.com/en-us/library/ms173179.aspx

Should Threads be avoided if at all possible inside software components?

I have recently been looking at code, specifically component oriented code that uses threads internally. Is this a bad practise. The code I looked at was from an F# example that showed the use of event based programming techniques. I can not post the code in case of copyright infringements, but it does spin up a thread of its own. Is this regarded as bad practise or is it feasible that code not written by yourself has full control of thread creation. I do point out that this code is not a visual component and is very much "built from scratch".
What are the best practises of component creation where threading would be helpful?
I am completely language agnostic on this, the f# example could have been in c# or python.
I am concerned about the lack of control over the components run time and hogging of resources, the example just implemented another thread, but as far as I can see there is nothing stopping this type of design from spawning as many threads as it wishes, well to the limit of what your program allows.
I did think of methods such as object injecting and so fourth, but threads are weird as they are from a component perspective pure "action" as opposed to "model, state, declarations"
any help would be great.
This is too general a question to bear any answer more specific than "it depends" :-)
There are cases when using internal threads within a component is completely valid, and there are cases when not. This has to be decided on a case by case basis. Overall, though, since threads do make the code much more difficult to test and maintain, and increase the chances of subtle, hard to find bugs, they should be used with caution, only when there is a really decisive reason to use them.
An example to the legitimate use of threads is a worker thread, where a component handling an event starts an action which takes a long time to execute (such as a lengthy computation, a web request, or extensive file I/O), and spawns a separate thread to do the job, so that the control can be immediately returned to the interface to handle further user input. Without the worker thread, the UI would be totally unresponsive for a long time, which usually makes users angry.
Another example is a lengthy calculation/process which lends itself well to parallel execution, i.e. it consists of many smaller independent tasks of more or less similar size. If there are strong performance requirements, it does indeed make sense to execute the individual tasks in a concurrent fashion using a pool of worker threads. Many languages provide high level support for such designs.
Note that components are generally free to allocate and use any other kinds of resources too and thus wreak havoc in countless other ways - are you ever worried about a component eating up all memory, exhausting the available file handles, reserving ports etc.? Many of these can cause much more trouble globally within a system than spawning extra threads.
There's nothing wrong about creating new threads in a component/library. The only thing wrong would be if it didn't give the consumer of the API/component a way to synchronize whenever necessary.
First of all, what is the nature of component you are talking about? Is it a dll to be consumed by some different code? What does it do? What are the business requirements? All these are essential to determine if you do need to worry about parallelism or not.
Second of all, threading is just a tool to acheive better performance, responsivness so avoiding it at all cost everywhere does not sound like a smart approach - threading is certainly vital for some business needs.
Third of all, when comparing threading symantics in c# vs f#, you have to remember that those are very different beasts in theirselfs - f# implicitly makes threading safer to code as there is no notion of global variables hence the critical section in your code is something easier to eschew in f# than in c#. That puts your as a deleloper in a better place bc you dont have to deal with memoryblocks, locks, semaphores etc.
I would say if your 'component' relies heavily on threading you might want to consider using either the parallel FX in c# or even go with f# since it kind of approaches working with processer time slicing and parallelism in more elegant way (IMHO).
And last but not least, when you say about hogging up computer resources by using threading in your component - please remember that coding threads do not necessarily impose higher resource impact per se – you can just as easily do the same damage on one thread if you don’t dispose of your objects (unmaneged) properly, granted you might get OutOfMemeory Exception faster when you make the same mistake on several threads…

Fibers in C#: are they faster than iterators, and have people used them?

So I was chatting with a colleague about fibers and turned up this paper from 2003 that describes a implementation of coroutines in C# using the Fiber API.
The implementation of Yield in this paper was for .NET 1.1, so it predates the yield return syntax that appeared in .NET 2.0.
It definitely looks, at first glance, that the implementation here is potentially faster and could scale across multiple CPUs rather well.
Has anyone used it?
I haven't used it, but I have an interest in the subject. Here's one nice implementation of coroutines in C# with a round-robin scheduler: http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=71235c5a-3753-4bab-bdb0-334ab439afaf
By the way, quoting wikipedia, "fibers describe essentially the same concept as coroutines". As far as I know, the closest thing to a coroutine (or a fiber) in C# are iterators. Actually, they are remarkably close to coroutines. Lippert posted several catches about iterators. Hopefully, none of them represent an serious problem for the purposes you need.
I have used yield-based "coroutines," and I have to say that they are a pain in the butt. The problem is, of course, that everywhere you want to use them, you're forced to use the yield syntax. Not only that, but unless you chain yields (parent yields child's yield), you can only ever nest your coroutines one level deep. This completely destroys one of the key benefits of coroutines (full stack save/restore).
I implemented a fiber-based coroutine system in C# and it worked wonderfully UNTIL I hit an exception. Unfortunately the .Net runtime stores a bunch of internal exception stuff in OS threads, which means that emulating multiple threads using OS fibers (and p/invoke) just won't work unless you'll never, ever, ever have an exception.
Coroutines, at very first glance catches my attention.. some days ago i was searching for workflow solution for parrallel AsyncWCF Method calls and what i found was really fascinating:
http://csharperimage.jeremylikness.com/2010/03/sequential-asynchronous-workflows-in.html
this article shows a very good use of coroutines to create/manage workflows in Silverlight application that consumes WCF using Async Pattern.
I don't know its speed w.r.t to iterators but to me its like an advanced form of subroutines that can be very helpful in mission critical tasks where a normal subroutine can't offer you the luxury to perform a task in parallel.

Is F# better than C# in scenarios where you need complete parallelism in parts of an application?

Is F# better than C# in scenarios where you need complete parallelism in parts of an application?
My main language is C# and I am writing an app where the core functionality built on top of the app (C#) has to be and planned to be very parallel.
Am I better of implementing these classes in F#?
I'd look at the Parallel Extensions that's being developed by Microsoft.
If you just need to process sets of data in parallel, the ParallelFX are very handy. They'll take a lot of pain out of doing it manually in C#.
But if the code has a lot of asynchronous code, F#'s async monad makes it vastly easier than can be done in C#. If you're looking at a lot of BeginXXX/EndXXX or the dreaded XXXAsync/XXXCompletedEvent code, then F# will be a major win.
Otherwise, you'll just have the general gains of F# over C#.
there are two ways of making things parallel, both of them work very well in F#.
As Josh already mentioned, there is a Parallel Extensions library. This make it extremely easy to parallelize processing of some data structures - especially immutable data structures that you'll often use in F#. So, combining Paraallel Extensions with F# is the right way to go. This will be discussed in my upcoming real-world F# book, but I'm making the source code available. This is covered in chapter 14 and the source for it should be available soon.
For some problems, you can use message-passing concurrency, which is an appealing alternative to shared memory. You can find some information about this in a free chapter from Don Syme's book. It'll be covered in my book as well (Chapter 13 & 16).
By combining message-passing concurrency with asynchronous workflows, you can get an excellent way for writing programs that cannot be easily parallelized using Parallel extensions (i.e. they need to share some information & also use asynchronous non-blocking operations (such as downloading from the internet))
According to this demonstration by Luca Bolognese, the ease of implementing parallelism is one of F#'s stronger points. At around 53 minute mark on, it gets quite impressive. Hope this helps a bit.
http://channel9.msdn.com/pdc2008/TL11/
F# has many advantages over C# in general and these play an equal role in the context of parallel programming but there is nothing about the F# programming language that makes it substantially more suitable for parallel programming.
In particular, there is a myth that shunning side effects and going purely functional is a panacea for parallelism but this is nonsense. You can make purely functional programs burn more cores more easily but getting competitive absolute performance and speedup on a multicore is an unsolved problem.
As others have already said, you will almost certainly want to use the Task Parallel Library that is now part of .NET 4. Note that the Visual F# 2010 standard library includes several functions that use the TPL, such as Array.Parallel.map.
F# is mostly free of side-effects so yes, but you wouldn't want to implement a UI in it. On the flip side, there will be a lot of parallel functionality built in to the next version of C# via LINQ.
You will also have to weigh your training requirements and the fact that F# is not yet RTM and won't be until late this year.
F# makes certain approaches better (e.g. native message support), but you can do it in C# if you minimise (or better, eliminate) mutable state.
As noted in other answers, .NET libraries are going to get a big boost in this way soon with the parallel extensions. These will have, however, exactly the same lack of scalability if you start using locks.

Categories

Resources