I currently have an application which is basically a wrapper for ~10 "LongRunning" Tasks. Each thread should keep running indefinitely, but sometimes they lock up or crash, and sometimes the wrapper app spontaneously exits (I haven't been able to track that down yet). Additionally, the wrapper application can currently only be running for one user, and that user has to be the one to restart the threads or relaunch the whole app.
I currently have a monitor utility to let me know when the threads stop doing work so that they can be manually restarted, but I'd like to automatically restart them instead. I'd also like the wrapper to be available to everyone to check the status of the threads, and for the threads to be running even when the wrapper isn't.
Based on these goals, I think I want to separate the threads into a Windows Service, and convert the wrapper into something which can just connect to the service to check its status and manipulate it.
How would I go about doing this? Is this a reasonable architecture? Should I turn each thread into a separate service, or should I have a single multi-threaded service?
Edit: All the tasks log to the same set of output files (via a TextWriter.Synchronized(StreamWriter)), and I would want to maintain that behavior.
They also all currently share the same database connection, which means I need to get them all to agree to close the connection at the same time when it's necessary. However, if they were split up they could each use their own database connection, and I wouldn't need to worry about synchronizing that. I actually suspect that this step is one of the current failure points, so splitting it up would be a Good Thing.
I would suggest you to stay inside one multithreading service if possible. Just make sure that threads are handled correctly when Service Stop is triggered. Put brake flags inside blocks of code that will take a lot of time to execute. This way you will make your service responsive on Stop event. Log any exceptions and make sure to wait for all threads to exit until service is finally stopped. This will prevent you to run same "task" in multiple threads.
Maintaining one service is in the end easier then multiple services.
Splitting to multiple services would be reasonable if you require some separate functionalities that can run or not beside each other.
I don't think moving the threads to a Windows Service removes any of the problems. The service will still crash randomly and the threads will still exit randomly.
I assume that your long-running tasks implement a kind of worker loop. Wrap the body of that loop in a try-catch and log all exceptions. Don't rethrow them so that the task does not ever exit. Examine the logs to find the bugs.
I'm currently building a C# application which will automatically authenticate a user against certain network resources when they connect to specific wireless networks.
At the moment, I'm using the Managed Wifi API to discover when a user connects / disconnects from a wireless network. I have an event handler, so that when any of these activities occurs, one of my methods is called to inspect the current state of the wireless connection.
To manage the state of the application, I have another class which is called the "conductor", which performs the operations required to change the state of the application. For instance, when the wireless card connects to the correct network, the conductor needs to change the system state from "Monitoring" to "Authenticating". If authentication succeeds, the conductor needs to change the state to "Connected". Disconnection results in the "Monitoring" state again, and an authentication error results in an "Error" state. These state changes (if the user requests) can result in TrayIcon notifications, so the user knows that they are being authenticated.
My current idea involves having the method used to inspect the current state of the wireless call the "authenticate" or "disconnect" methods within the state manager. However, I'm not sure if this is an appropriate use of the event handler -- should it instead be setting a flag or sending a message via some form of IPC to a separate thread which will begin the authentication / disconnection process?
In addition to the event handler being able to request connection / disconnection, a user can also perform it via the tray icon. As a result, I need to ensure these background operations are not blocking the tray's interactions with the user.
Only one component should be able to request a change of the system state at any time, so I would need to use a mutex to prevent concurrent state changes. However, how I should synchronous the rest of these components is a slight mystery to me.
Any advice or literature I should read would be appriciated. I have no formal training in C# language, so I apologize if I've misstated anything.
EDIT: Most importantly, I want to verify that an event will be executed as a separate thread, so it cannot block the main UI. In addition, I want to verify that if I have an event handler subscribed to an event, it will handle events serially, not in parallel (so if the user connects and disconnects before the first connection event is processed, two state changes will not be occurring simultaneously).
Any advice or literature I should read would be appriciated. I have no formal training in C# language, so I apologize if I've misstated anything.
That explains a few things. :)
I would read up on threads, event handling, and creation of system tray icons/interfaces.
It is important to note the following:
Events are processed on the same thread they are called from. If you want the processing of an event not to lock the GUI then you will need to have the button move the work to a different thread.
When an event is fired it passes the appropriate arguments to all the methods in its list. This is pretty much the same as calling one method which in turn calls all the others (see EventFired example). The purpose of events is not to call methods as we can do that already, it is to call methods which may not be known when the code is compiled (the click event on a button control would not be known when the library the control is in is compiled for example). In short, if you can call the method instead of using an event the do so.
void EventFired(int arg1, object arg2)
{
subscribedMethod1(arg1, arg2);
SubscribedMethod2(arg1, arg2);
SubscribedMethod3(arg1, arg2);
SubscribedMethod4(arg1, arg2);
SubscribedMethod5(arg1, arg2);
SubscribedMethod6(arg1, arg2);
SubscribedMethod7(arg1, arg2);
}
If you want to prevent a user interface from locking do the work on another thread. Remember though, user interface elements (forms, buttons, grids, labels, etc.) can only be accessed from their host thread. Use the control.Invoke method to call methods on their thread.
Removing an option from an interface is not a good way to prevent raceway conditions (the user starts a connect/disconnect while one is already running) as the user interface will be on a different thread and could be out of sync (it takes time for separate threads to sync up). While there are many ways to resolve this problem, the easiest for someone new to threading is to use a lock on the value. This way .NET will make sure only one thread can change the setting at a time. You will still need to update the user interface so the user knows the update is occurring.
Your general design sound fine. You could use 2-3 threads (1 for the user interface (tray icon), 1 for checking for new network connections, and 1 (could be merged with connection check) which checks the internet connection.
Hope this helps, let us know if you need more (or accept an answer).
As an option, alternative...
If I were you, and since you're starting anew anyway, I would seriously consider the
Rx Reactive Extensions
It gives a completely fresh look at events and event based programming and helps a lot exactly with the things you're dealing with (including synchronizing, dealing with threads, combining events, stopping, starting etc. etc.).
It might be a bit of a 'steep curve' to learn at start, but again, it might be worth it.
hope this helps,
To me it seems that you're going to overengineer the project.
You basically need to implement an event in Commander and in main application subscribe to them. That is.
If there is always one component can make a change and you can have more then one, using some sync mechanism, like a Mutex noted by you, is perfectly valid choice.
Hope this helps.
If you want to have at most one state change pending at any time it is probably best to have the event handlers of the external events you are listening to hold a lock during their execution. This ensure an easy way to program because you are guaranteed that the state of your app does not change underneath you. A separate thread is not needed in this particular case.
You need to make a distinction between the current state of the application and the target state. The user dictates the target state ("connected", "disconnected"). The actual state might be different. Example: the user wants to be disconnected but the actual state is authenticating. Once the authentication step is completed the state machine must examine the target state:
targetState == connected => set current state to connected
targetState == disconnected => begin to disconnect and set state to disconnecting
Separating actual and target state allows the user to change his mind any time and the state machine to steer towards the desired state.
It's hard to give a precise answer without seeing the whole (proposed) structure of your app. But in general, yes, it's OK to use an event hander for that sort of thing - though I'd probably move the actual implementation out to a separate method, so that you can more easily trigger it from other locations.
The comment about disabling the "Connect" button sounds right on to me, though it's quite conceivable you might need other forms of synchronization as well. If your app doesn't need to be multi-threaded, though, I'd steer away from introducing multiple threads just for the sake of it. If you do, look into the new Task API's that have been included as part of the Task Parallel Library. They abstract a lot of that stuff fairly well.
And the comment about not over-thinking the issue is also well-taken. If I were in your shoes, just beginning with a new language, I'd avoid trying to get the architecture just right at the start. Dive in, and develop it with the cognitive toolset you've already got. As you explore more, you'll figure out, "Oh, crap, this is a much better way to do that." And then go and do it that way. Refactoring is your friend.
I have built a component library that includes an executive class which does work on any number of threads and fires events from these threads. This is all good. Now I want to use my executive in a desktop app. (Winforms in the first instance, WPF later on) so I want to marshall all event calls back onto the UI thread. I know of a 3 ways to do this;
Check IsInvokedRequired/call Invoke in the handlers; This is lame IMO.
Create a decorator for the executive that uses the event base async model; Gives me the desired result, not very exciting though.
Use the WPF dispatcher; feels wrong to use a WPF class in Winforms app. or even more wrong to use it in the component lib.
I have spent the last hour or so reading up on Rx and I'm thinking the ideal solution might be to bake Rx into the executive and have the executive take (optionaly) a scheduler. This way the client of the executive can determine the behaviour with regard to the which thread/s the events are raised on and I get all of the other Rx goodness. Or perhaps create an RxExecutive that takes a Scheduler and encapsulates my existing executive to provide an Rx API.
Am I thinking along the right lines or have I missed the point?
Rx does provide a very nice way to access the UI thread in a Windows Forms app. You can use the full Rx library of observables, but if you just need an easy way to run things on the UI thread then using the ControlScheduler is a snap.
Assuming you have a form called form1 just do this:
var scheduler = new System.Reactive.Concurrency.ControlScheduler(form1);
scheduler.Schedule(() => { /* Do Stuff on UI thread */ });
Easy.
You don't have to use a reference to the form - you could use any control.
I believe the preferred pattern is to specify the scheduling SynchronizationContext. SynchronizationContexts are available for both WPF and WinForms applications, are used to schedule WF4 and WCF, and I'm sure are also used in other parts of the framework.
You are on the right track. Alternatively, you could have the users that care about the thread use ObserveOn. The advantage of this is that only the observer code is run on the needed thread.
I have a problem understand how Workflow Scheduler works, my architecture is the follow: I have several operations that call asyncronously a service from UI, it inizialize a new WorkflowApplication and calls Run() method, than it take some time to accomplish the operation, it goes through some steps and than an activity does the big work
I understand the workflow scheduler can process one workflow instance at time, but while workflows are running that seems to "freeze" my entire website, I can't access any other service, it become slow until all workflows finish. (I have also tried to call service just once and start all workflow inside it but the behavior is pretty the same)
Could someone help me understand that? There is some way to avoid this?
First impression is that there is thread starvation, or something similar with another resource contention, going on.
Are you using a WorkflowApplication or a WorkflowServiceHost to execute your workflow? I believe the first but it isn't quite clear in your question.
If you are using a WorkflowApplication: Are you setting the SynchronisationContext and are you waiting for the workflow to complete before finishing the request?
How many workflows are you starting and approximation how many ASP.NET requests are there being executed?
I come to you to see if someone has an idea on how to solve a problem I've come across while doing a migration to ActiveMQ.
I'm using ActiveMQ to send notifications within this project (in C#), and after finishing the implementation i found some errors concerning threading problems. (
I know that the solution for that exception is to use the "if this.InvokeRequired.... etc", but my question is:
Is there any way of finding all the methods that require this invoke?
Of course i could check step by step all the events triggered with the notifications, but, apart from the fact that it would take me too much time, it wouldn't solve me future programming errors.
I guess there is a better way to figure out this, but i cannot think of it right now. Have you encountered the problem before?
Thank you very much for your help
No. There is no automated way to do this, unless of course you've setup a test driven project from the beginning. In which case, you could add some conditions to test for thread correctness.
Software cannot deduce what you intended, except in very specific ways (FxCop for instance, and the IDE's warnings about certain things). What you wrote is not necessarily what you meant to write. You're effectively asking for software that can figure out what you meant to do.
The only way to know if an invoke is required is to know the context in which any given function operates. If it operates on a background thread, and you are calling code that needs to run on the main thread (such as GUI code) then an invoke is required.
You have to figure that out yourself.
Its not that certain methods you are calling require the invoke. It depends on what thread you are calling those methods from.
If you're calling a method in a Winforms app, on a thread other the UI thread, it's going to require the Invoke.
Depending on the code, it should be easy to analyse what calls are made from which threads, especially if you are naming background threads (which always comes in handy). But there's probably not an automatic way to do this - just step back and look at your code.