I have a C# winforms project which has a reference to a library also coming from myself. The winforms app triggers some work to do for the library. Is it possible that the library can finish its work even if the winforms app gets closed?
There are two possible approaches:
create a separate subprocess. Ending the parent process will not end the child, thus, the newly created task will continue when the parent app is closed
make the parent app in such way that closing the main form doesn't end the application, thus, giving the application time to end all worker threads spawned during its lifetime
I am not sure which of the two I would recommend, both seem risky as chances are the long-running background operation will not finish in reasonable time. And then what?
Is it possible that the library can finish its work even if the
winforms app gets closed?
No, not if that library is simply hosted in the main process.
You would need to do something along the lines of create a windows (or web) service and host the library in the service along with a message passing mechanism. Then call into it by having your windows application call a command on the service.
Related
I am working on a project where we have lots of separate components are running and my agenda is to cancel the component process in between based on user input.
For example: I have 6 windows service that do all the work and 1 another windows service that is responsible for distribution of work. so once the work is send to worker windows service there is no control over it. this worker windows service do some time consuming task, calling several function, interect with database etc. I want to cancel the task in between of working.
The traditional approch we use for cancelation will no longer work here as...
1. I am not iterating any loop where I can continuosly check for Cancel flag.
2. Since the component is totally separate and once they start working, new instance is created of that component and not able to pass any value to that component.
Thanks in advance.
I've got a few instances of the same class. During the classes lifetime, every method call on this class should be executed on the same thread. But for each instance I need a different thread.
I thought about Threadpool, but it seems that I have too less control about it.
How can I reuse a thread without using ThredPool?
Thank you! Martin
Edit (why I need this):
I have to use a win32 dll to access business logic of a third-party product. This dll is not designed for a multi-threaded environment like a web application. When I run my ASP.NET MVC application in ASP Classic Mode (STA Thread), everything works fine so far. But the problem is that all users going to block each other. This component also maintains some state. As soon as a different thread is accessing this component, it will not recognize the connection-handle I have to pass in for each method call. I got the connection handle after a logon procedure. I want to put my web application in MTA mode back again and use a worker-concept, assigning about 10 users to a worker (max. 10 users should block each other). One worker should always use the same thread to execute the api calls so the component will not stubmle.
I'm not happy with this situation, but I have to find am acceptable solution.
Update - Found a Solution:
Thanks to the "Smart Thread Pool" from Ami Bar I could accomplish the behavior I was looking for (easily). For each worker, I have now my own thread pool instance with a max and min number of one thread. Well, it's not the idea of a thread pool, but it makes it very easy to handle the work-items and it also has some nice other featrues. The web application is running on MTA now.
I'm going to prepare some load tests to see if its stable over hours.
see here: http://www.codeproject.com/Articles/7933/Smart-Thread-Pool
I've made a project than uses tcp sockets connectivity (own closed protocol), added background connectivity with Network Trigger API, as described here (starting from page 17) - StreamSocket control channel registration block, and IBackgroundTask class, that should be fired each time socket receives something.
Have tried everything to debug the code in background task, with no use:
closing the visible app with a gesture
lock the screen
tried to load some other heavy application, to make windows suspend my app
All these have not helped me to make background task run (and debug) during socket message. What am I doing wrong? Should I have to get the separate suspendable device, like a WinRT tablet, to get this working?
By default referenced projects are not added to the main one. This is not so obvious as it may seem, and that's why I spent almost a week to find out this. So the clue is: check reference projects accessibility.
Upd:
There are some more things to deal with, as I've found out during development. Some of them are not as clear as they need to. Here is a list of what I did:
Add background project to main project's references (right click on references node in solution browser).
Check if main project manifest contains right declaration (background task w/control channel, right background entry point name with full package, $targetnametoken$.exe as executable)
A thing that leads from #1: all the entities you plan to use within background, should be put into separate project in solution. This project is then referenced by both main and background projects.
Be aware of BackgroundExecutionManager.RequestAccessAsync() to be called before registering ControlChannelTrigger
A key thing I've found just in one small comment in a sample project:
// IMPORTANT: When using winRT based transports such as StreamWebSocket with the ControlChannelTrigger,
// we have to use the raw async pattern for handling reads instead of the await model.
// Using the raw async pattern allows Windows to synchronize the PushNotification task's
// IBackgroundTask::Run method with the return of the receive completion callback.
// The Run method is invoked after the completion callback returns. This ensures that the app has
// received the data/errors before the Run method is invoked.
// It is important to note that the app has to post another read before it returns control from the completion callback.
// It is also important to note that the DataReader is not directly used with the
// StreamWebSocket transport since that breaks the synchronization described above.
// It is not supported to use DataReader's LoadAsync method directly on top of the transport. Instead,
// the IBuffer returned by the transport's ReadAsync method can be later passed to DataReader::FromBuffer()
// for further processing.
More info here - http://code.msdn.microsoft.com/windowsapps/ControlChannelTrigger-91f6bed8/sourcecode?fileId=57961&pathId=2085431229
If you did all things properly, the debugging of background tasks is straightforward. Just put the breakpoint and go on, nevermind of main project is running or suspended.
ps - If the project is suspended, be aware of calling UI thread (especially awaited things) - they won't run until app is running, and will wait.
I'm trying to interact with a third party application but whenever I try and call a method, I get an error message saying System.InvalidOperationException: Operation must be performed on the application thread. The exception is of type System.Reflection.TargetInvocationException and I'm guessing this is because my app is running in a completely separate process. Is there a way to get my program, which is a console application, to start running on the same thread as the third party app?
You can't get two separate applications to run in a single thread.
If you are trying to interact with some UI controls in your application, you can use .Invoke() to make sure the relevant code is executed in the UI thread.
If you're trying to manipulate the a third party application, the appropriate solution depends entirely on how you're interacting with it. Does it provide an API? Sending messages to its window handle? ??
In order to interact with a running instance of another application, you'll need to use something like remoting (obsolete) or WCF. Essentially, the other application acts as a server, and you have to somehow connect to it. Referencing its assembly, instantiating one of the classes therein defined and calling methods on that instance won't let you talk to an already-executing process.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
windows service vs scheduled task
Windows Service Vs Simple Program
I'm trying to create a program that runs periodically (say every 5 minutes), or have the program running and have it execute the function within it (every 5 minutes).
The program is to obtain data from a database when it's executed and then write this to (for now) say info.txt file (no sensitive stuff is contained in here). each time it writes to the file it should overwrite the existing info within the file.
The program should also be started automatically at windows start up. (thus no need to login on the machine and to execute the .exe [if it's a normal program and not a service])
In between the periods that it executes the program would have nothing to do.
Therefore, should I run this program as a Windows Service, or should I use the Task Scheduler to periodically start the program to do this?
My goal is for this program to run as smooth as possible without clogging up resources. (eg. it shouldn't need more than 5% of the cpu)
I hope my question was clear enough.
I would go with application that is triggered by task scheduler. Only thing that you need to worry about is to run single instance of your application.
You can set task to run under specific user account and to run even if user is not logged on. There are number of events that can trigger task star like "Windows start", "System Idle"...
Other advantage is: If something crashes you can set task scheduler to send you an email or alert you in number of ways. You can control "exit code" of your application and signal to task scheduler what's going on and what to do.
There are a lot of positive features that task scheduler offers but not many people are using them.
I would suggest a Windows Service for this. Might be a good idea to create both and compare what the resource usage is like anyway?
I would actually recommend going for both depending on the requirements of the task you wish to run. I generally build most functionality for scheduled services into a single class library and then wrap it in a console application to start with and for debugging. When satisfied I wrap it in a windows service and forget about it.
Considerations of using a console app:
Make sure you run it under system account if possible or you can put in a specific login under Run as in scheduler. This will ensure an interactive login is not required.
If having 2 instances of it running at the same time is a problem, make sure you name it clearly and check for an instance of it running in your main method and exit if it is. A windows service will avoid this issue.
Considerations of using a window service
Make sure you're educated on thread usage. Windows services will use less resources if managed properly, but can be tricky if it's new to you and end up leaking memory in timer based tasks.
..there's a lot more to consider, but code it right and you can start with one and move to the 2nd when you're confident about it.