This is far-fetched I know but I have to ask. Is there a way to specify the thread that a BackgroundWorker instance is to use? Or at least some way to force it onto another specific thread (whose reference I have). I have a large project that makes use of BackgroundWorker, and I have just recently started using some in-house FRAMEWORK (I have to) that uses Thread instead, and the two seem not be happy with each other (I know the reason but I can not fix it as it is in the framework whose guts I can modify) that is why I ask this question, before I spend days converting my project to use FRAMEWORKS Threading functions.
You might be able to derive from the BackgroundWorker class as it's not sealed and override the methods for RunWorkerAsync etc. Would be painful and easy to introduce bugs, but that would give you the ability to kick off the DoWork event onto your in house thread framework.
Related
I'm not so much seeking a specific implementation but trying to figure out the proper terms for what I'm trying to do so I can properly research the topic.
I have a bunch of interfaces and those interfaces are implemented by controllers, repositories, services and whatnot. Somewhere in the start up process of the application we're using the Castle.MicroKernel.Registration.Component class to register the classes to use for a particular interface. For instance:
Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient
Recently I became interested in creating an audit trail of every class and method call. There's a few hundred of these classes so writing a proxy class for each one by hand isn't very practical. I could use a template to generate the code but I'd rather not blow up our code base with all that.
So I'm curious if there's some kind of on the fly solution. I know nHibernate creates proxy classes at some point which overlay all the entity classes. Can someone give me some guidance on how I might be able to do something similar here?
Something like:
Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient
Obviously that won't work because I can only use generics to generalize the types of methods but not the methods themselves. Is there some tricky reflection approach I can use to do this?
You are looking for what Castle Windsor calls interceptors. It's an aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:
Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.
If you want to apply it to many registered services, read more about interceptor selection mechanisms: IModelInterceptorsSelector helps there.
Using PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.
I'm creating a Windows Tray App which doesn't use the Application Framework. The startup object is a module sub, which makes calls to a class to create the app icon directly in the tray without opening any forms.
I've just started reading about the Singleton Pattern, with the intention of making the app single-instance. This seems to be the way it should be done, but...appearance and reality are not the same. What looks good may not be.
Is singleton the best way to make a tray app single-instance?
Are there other ways that should be considered?
Are there any common problems that arise when developing with these ways?
There seems to be a fundamental misunderstanding of what a singleton is that is leading you astray. A singleton is a class that enforces that there can only ever be one instance of the class throughout the lifetime of an application.
The singleton pattern doesn't apply to applications as a whole.
If you require that the application restrict itself to only allow one instance to be running at any given time then, what I have done in the past is to have your app check the running processes on the computer as soon as it starts. If it finds any that have the same name as what your app is called then the second instance stops itself.
The flaw with this approach is that there is nothing to say that some external application can't have the same name as your application(however unlikely that may be)
I've never really looked into it beyond that so I can't comment on any other viable options.
I have read a LOT of material about Windows Form projects not supporting MTA. I get it. However, I also have read about Background worker, async/await and BeginInvoke use with such solutions. This and this are just a couple of examples. Here's one that even uses MSMQ. Some of the examples I have reviewed go way back to VB6 days.
I need to augment a Windows Form project with code to interact with a vendor service via API calls that could benefit from async capability. This being 2014, what is the best way to approach this? I use VB NET and have VS 2010 for my development.
Ideally, I would like to create a class library with the logic to interact with the vendor and just return the results to my Windows Form project. Can that be done?
The fact that MTA is not supported doesn't mean that you can't use multiple threads. The MTA model is just one way to use multiple threads, but because it's difficult to implement objects for that model, Windows Form uses the STA model instead.
The important effect of this is just that it means that the main thread in the application takes care of everything that has to do with the user interface. You can start as many threads as you like/need, but whenever anything from those threads needs to be displayed in the user interface, they have to use the Invoke method to let that update be done in the main thread.
There are already asynchronous method in the framework, for example the BeginRead and BeginWrite methods in the System.IO.FileStream class. You can have a look at those for some hints on how asynchronous methods are used in the framework.
If the API is synchronous, you would make asynchronous methods by simply starting a new thread that does the API call and then executes a callback method when it is done. As it's that thread that is waiting for the response, the call doesn't occupy the main thread.
Is there a way around using the Invoke and InvokeRequired methods for objects which were created in other threads? Is there a method which is more direct and less memory intensive? Perhaps a state machine or thread controls?
Am I wasting my time worrying about this method's resource usage?
I'm using this invoke method: http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/
I'm using VB.NET in VS 2012
This strongly fits my doctor's usual advice: "if it hurts then don't do it".
There are several .NET patterns that emphasize keeping the threaded code separate from code that needs to run on the UI. BackgroundWorker has been available for a long time, note how its ProgressChanged and RunWorkerCompleted events run on the UI thread. Good place to update UI without having to invoke yourself.
The .NET 4 Task class hands you the TaskScheduler.FromCurrentSynchronizationContext() method. Which is a good way to chain a task that runs on the UI thread, pretty specifically intended to update the UI with the results of previous tasks that run asynchronously. VS2012 provides yet another weapon with the Async and Await keywords. All good ways to avoid writing the code you don't want to write.
My iPad app syncs with an XML feed, running the sync in an NSOperation subclass executed from an NSOperationQueue. As it parses the feed, it calls back to the main thread via performSelectorOnMainThread:withObject:waitUntilDone: to update various parts of the UI, schedule downloads, etc. Some of this is pretty expensive; the UI can sometimes become unresponsive for a second or two as a sync is going on.
To make the UI more responsive, I've removed the use of performSelectorOnMainThread:withObject:waitUntilDone: in favor of direct calls to perform all the sync-related tasks, including updating the UI. So now the sync takes place entirely on the background thread created by the NSOperationQueue. This seems to work pretty well, and the UI is much more responsive during a sync.
However, I'm leery of releasing with it this way. I've seen some mentions in various places that one should only update the UI on the main thread (example with reference to AppKit). But I've been unable to find anything specific on this topic in the documentation.
So how important is it to update the UI on the main thread? Which parts of an app are thread-safe and which are not? Is there perhaps a reference explaining what's safe to execute in an NSOperation and what should be executed only on the main thread in iOS? Am I really doing something unsafe or crash-prone?
It is extremely important that you always update the UI on the main thread. Touching the UI from a background thread can cause all sorts of issues, including corruption of internal state, crashes, or just plain incorrect behavior. Any work that doesn't require touching the UI should go ahead and do on the background thread, but the bits of code that update the UI definitely needs to happen on the main thread.
The Thread Safety Summary in the Threading Programming Guide discusses which Foundation classes are thread-safe and which aren't. The whole summary is worth a skim for quick answers to common questions.
The Thread Programming Guide also has a very brief section on Threads and Your User Interface, where “it is recommended that you receive user-related events and initiate interface updates from your application’s main thread,” and “Some frameworks, such as Cocoa, generally require this behavior.” No cross-reference to a discussion of this Cocoa requirement, but I imagine I'll run across it eventually.
But the upshot is that, according to this document it is important to perform UI updates on the main thread.
Are you sure you need the NSOperation? NSXMLParser.parse and NSURLConnection.start are already asynchronous. If the class that you're parsing updates some model object, and your view controller observes that model object using KVO, you might wind up with simpler, better performing code.
There is further documentation and discussion in a technical note that goes with the ListAdder sample code. It's TN2109: 'simple and reliable threading with NSOperation'. It repeatedly talks about only updating UIKit elements from the main thread and gives examples of correct and incorrect implementations. You might find further references to it by searching 'thread confinement'.