Can anyone give me an example scenario where Asynchronous Callback should be used in an Winforms Database application?
And also an example scenario where Asynchronous Callback must be used in an Winforms database application?
I can't give you a sample of when you must use asynchronous calls, but in general you would want to make any database call that might take a long time in an asynchronous manner to keep your UI responsive and offer the user the possibility to cancel the operation. An given the nature of database call, most (if not all) of them would qualify.
Regarding the method of achieving the asynchronousity, I would probably prefer using a BackgroundWorker over using Begin/EndInvoke and IAsyncResult.
Related
I'm far from new at threading and asynchronous operations, but SL seems more prone to asynchronous issues, particularly ordering of operations, than most frameworks. This is most apparent at startup when you need a few things done (e.g. identity, authorization, cache warming) before others (rendering a UI usable by your audience, presenting user-specific info, etc.).
What specific solution provides the best (or at least a good) strategy for dealing with ordering of operations at startup? To provide context, assume the UI isn't truly usable until the user's role has been determined, and assume several WCF calls need to be made before "general use".
My solutions so far involve selective enablement of UI controls until "ready" but this feels forced and overly sensitive to "readiness" conditions. This also increases coupling, which I'm not fond of (who is?).
One useful aspect of Silverlight startup to remember is that the splash xaml will continue to be displayed until the Application.RootVisual is assigned. In some situations (for example where themes are externally downloaded) it can be better to leave the assignment of the RootVisual until other outstanding async tasks have completed.
Another useful control is the BusyIndicator in the Silverlight Toolkit. Perhaps when you are ready to display some UI but haven't got data to populate the UI you assign the RootVisual using a page that has a BusyIndicator.
In my oppinion:
1st: Render start up UI that will tell the user, that the application did register his action and is runing, (Login window may be?)
2nd: Issue neccessary calls for warm up procedures in background (WCF calls and all that) and let user know about progress of tasks that are required to finish before next GUI can be made operable (main window?)
Order of operations is kind of situation specific, but please be sure to let user know what is happening if it blocks his inputs.
The selective enabling of individual controls can look interesting, but user might go for that function first and it will be disabled, so you have to make sure user knows why, or he will be confused why at start it was disabled and when he went there 10mins later it works. Also depends on what is primary function of your program and what function would that disabled control have. If application main function is showing list of books it wouldnt be nice to make that list load last.
Sorry for yet another question about EF4 context lifespan, but I've been wondering about this for a while and I do not seem to find the answer. I'm not very familiar with lots of patterns or overcomplicated stuff (in my point of view) so I want to keep it simple.
I work with an ASP.NET application where the context is managed by each http request which is a very good approach in my opinion.
However I'm now working with a winforms application and I sometimes have transactions or reports that will not perform very well if I simply create the context for each query. Not that this performance issue is a very problematic thing, I just want to hear if there's a simple strategy as per HTTP request in ASP.NET for winforms?
Don't create a context for each query. At the same time, don't create a context that gets used for the entire lifetime of a Form (or your application).
Create a context for a single Unit of Work (which can encompass many queries).
That way you have all of your changes encapsulated in the context and you let Entity Framework wrap the database calls in a pretty little transaction without having to worry about it yourself.
I prefer to abstract the Repository and Unit of Work patterns out of the Entity Context so that I can use them independently (which makes everything very clear). MSDN actually has a decent article on the details:
MSDN - Using Repository and Unit of Work patterns with Entity Framework 4
I'm writing a WPF application using a MVVM pattern and using Prism in selected places for loose coupling, and I'd like to have logging messages shown in a window and written to a file. The subset of messages going each way may not be the same.
I think I should publish a message through the EventAggregator (MS-Prism implementation of observer pattern) and have two objects subscribe: one that updates the LogWindowViewModel and one that logs using the Enterprise Library logger. Is this a good idea or am I duplicating something that's already implemented?
The fact that the log message will be different in each output is the limiting factor.
Extending the block may suffice and defining a CustomTraceListener or ILogFilter may work out for you. This would avoid needing to use the EventAggregator.
It boils down to who has the knowledge of what and where to log. Are the differences driven off values within the logging engine such as severity? Are they instead driven by the consumer of the logging engine and therefore tightly coupled to the class itself? These types of questions will dictate your choice.
Leveraging the extension points in the logging block would be my first choice before having to rely on using the EventAggregator.
I think an idea is fine. There is not so much functionality to be duplicated it seems
I used Common.Logging as data collector, filter and distributor for something comparable and wrote a custom appender for my own processing and ui-output.
In my WPF application I need to do an async-operation then I need to update the GUI. And this thing I have to do many times in different moment with different oparations. I know two ways to do this: Dispatcher and BackgroundWorker.
Because when I will chose it will be hard for me to go back, I ask you: what is better? What are the reasons for choosing one rather than the other?
Thank you!
Pileggi
The main difference between the Dispatcher and other threading methods is that the Dispatcher is not actually multi-threaded. The Dispatcher governs the controls, which need a single thread to function properly; the BeginInvoke method of the Dispatcher queues events for later execution (depending on priority etc.), but still on the same thread.
BackgroundWorker on the other hand actually executes the code at the same time it is invoked, in a separate thread. It also is easier to use than true threads because it automatically synchronizes (at least I think I remember this correctly) with the main thread of an application, the one responsible for the controls and message queue (the Dispatcher thread in the case of WPF and Silverlight), so there's no need to use Dispatcher.Invoke (or Control.Invoke in WinForms) when updating controls from the background thread, although that may not be always recommended.
As Reed said, Task Parallel Library is a great alternative option.
Edit: further observations.
As I said above, the Dispatcher isn't really multithreaded; it only gives the illusion of it, because it does run delegates you pass to it at another time. I'd use the Dispatcher only when the code really only deals with the View aspect of an application - i.e. controls, pages, windows, and all that. And of course, its main use is actually triggering actions from other threads to update controls correctly or at the right time (for example, setting focus only after some control has rendered/laid-out itself completely is most easily accomplished using the Dispatcher, because in WPF rendering isn't exactly deterministic).
BackgroundWorker can make multithreaded code a lot simpler than it normally is; it's a simple concept to grasp, and most of all (if it makes sense) you can derive custom workers from it, which can be specialized classes that perform a single task asynchronously, with properties that can function as parameters, progress notification and cancellation etc. I always found BackgroundWorker a huge help (except when I had to derive from it to keep the Culture of the original thread to maintain the localization properly :P)
The most powerful, but also difficult path is to use the lowest level available, System.Threading.Thread; however it's so easy to get things wrong that it's not really recommended. Multithreaded programming is hard, that's a given. However, there's plenty of good information on it if you want to understand all the aspects: this excellent article by our good fellow Jon Skeet immediately jumps to mind (the last page of the article also has a good number of very interesting links).
In .Net 4.0 we have a different option, Task Parallel Library. I haven't worked with it much yet but from what I've seen it's impressive (and PLINQ is simply great). If you have the curiosity and resources to learn it, that's what I'd recommend (it shouldn't take that much to learn after all).
BackgroundWorker is nice if you're doing a single operation, which provides progress notifications and a completion event. However, if you're going to be running the same operation multiple times, or multiple operations, then you'll need more than one BackgroundWorker. In this case, it can get cumbersome.
If you don't need the progress events, then using the ThreadPool and Dispatcher can be simpler - especially if you're going to be doing quite a few different operations.
If C# 4 is an option, however, using the Task Parallel Library is a great option, as well. This lets you use continuation tasks setup using the current SynchronizationContext, which provides a much simpler, cleaner model in many cases. For details, see my blog post on the subject.
How should I have the NHibernate Session Factory and the sessions for a WinForms application?
Should the SessionFactory be a singleton? Or can I create it every time? What about sessions and transactions?
Any help would be appreciated. Thanks
The session factory should be a singleton since it is expensive to create. It is thread safe so there is no threading issue with using it.
I have used the session-per-conversation pattern in winforms applications, and have found it to work well. With this pattern you use the same session for a series of operations that belong together. As I see it, a conversation in a winforms app could, roughly, be mapped to a GUI operation in your application.
Using a new session for every GUI operation helps keep the session small enough to to avoid performance problems with to many entities in the first level cache, while at the same time avoiding using a separate session for every operation, which also can cause performance problems.
To implement this you then create a new session before handling the GUI command, and when the command has been handled you dispose the session. Below is an example of this, which uses a class (PersistenceContext) that creates a session when it is instantiated and disposes the session when it is disposed. This class can then create repositories that use the current session.
public void SomeGuiEvent(...)
{
using (var context = new PersistenceContext())
{
ProcessStuff(context);
}
}
There are ofcourse many other options of how to implement this, but however you choose to implement it, I can recommend the Session-per-conversation pattern when using NHibernate in a Winforms app.
Here is an msdn article showing sample application built by Oren Eini (Ayende Rahien): Building a Desktop To-Do Application with NHibernate
This has been asked a few times on Stack Overflow.
The Session Factory should be a singleton, because they are expensive to create.
For Sessions, there seems to be a rough consensus on a "one session per form" approach for NHibernate and WinForms. This means you should open a session when you open a form that accesses your database, and close the session when you close the form.
Look at the answers to this question -
What should be the lifetime of an NHibernate session? - for some more detailed descriptions, and some good links for further reading.