access specific worker process on application pool which has multiple processes - c#

I have an application pool that has multiple worker processes (e.g 4). Is there somehow any way to access the website, such that you know you are always on worker process #1, or #2, etc?
I need to do specific tasks like clearing memory cache on a particular worker process, and since you don't know which one you are on, I'm finding it a problem to clear the cache for all the worker processes.

Make a request loop until System.Diagnostics.Process.GetCurrentProcess().Id returns the process you want to work with.

Related

How to kill all child threads in C#?

Suppose, I have a server application. This application polls for incoming clients in a separate child thread. Also, sub-threads are spawned for each of the incoming clients to service their requests separately.
I want to kill all threads except the Server application's main thread, say, by clicking a button.
How can I do that?
This application polls for incoming clients in a separate child thread.
Okay, so it seems you are the one creating those threads. Can't you just keep a list of threads and then call Abort on them all? That seems the most straight-forward approach. (But be aware of some caveats)
If that is not possible, you could get a list of all threads, filter them on their name or some other characteristic, and Abort those.
A better approach is to use tasks, which are far better manageable than threads. You might want to read up on TPL.

Thread IIS wont start C#

Before I go into this question, I d like to say that, I have read the threading modeling for IIS 7, 7, 7.5 so I know how threads are handled.
My application starts a thread when a request comes in.
We can assume the threads as cron jobs.
GET request comes in, Lets say /Handle
in the scope of /Handle I start a thread from that action , THREAD A
I am not long polling the GET request, so it returns back to the
user right away. So thread handling the GET is returned to the POOL
Then I wait until the thread A completes to do anything else.
So No threads are running as far as I know. Both the thread that was
handling the GET and THREAD A has exited.
I make the same request a few times SEQUANTIALLY. I always wait for both threads to exit.
After a while `Thread.Start()1 function blocks.
Questions :
I know that the threads are returning and I am not leaking any ghost threads.
Why does IIS not allowing me to start new threads after a like 4-5 requests. ?
What is the right way to create application thread for the user application.
If I said Thread t= new Thread(), does this allocate a thread from the pool that handled the GETS or CLR?
I am using IIS7.
I know that I exit each thread, I call a JOIN on THREAD A , and it never blocks, and at this point I am not worried about scalability so I always have ONE user hitting the server sequentially.
So to answer your question "What is the right way to create application thread for the user application?" (i.e. ASP.NET application) - You have many options:
run on the ASP.NET thread, without any threading - ASP.NET will still handle more then one request
use async calls (see async operations) for long running operations
use CLR ThreadPool
send a message to some other server (e.g. using WCF services), so the long running processing takes place outside the Web server.
You mentioned reading about threading in ASP.NET, but in "MSDN: Performing Asynchronous Work, or Tasks, in ASP.NET Applications" there's a relatively short description of how threading in ASP.NET works. At the end of the post, there's a question:
"Q4: Should I create my own threads (new Thread)?" and the answer for that question is "A4) Please don’t (create new Threads). Or to put it a different way, no!!! (...) ".
And to answer your question: "Why does IIS not allowing me to start new threads after a like 4-5 requests"?
That's really a strange behaviour, maybe IIS knows that your are doing it wrong ;)

Setting a low thread priority for a heavy load task

First, thanks for all the replies!
I want to be more specific - I have a website that shows some current and historical reports. I want to be able to allow users to delete all or some of the history, while still navigating the website.
Therefore, I want to run a separate thread that will handle deleting the data, but I want to give this thread a low priority so it doesn't make the web site slow or unresponsive.
I'm in the design phase right now and I'd appreciate some strategy suggestions. Thanks!
You should be fine. Lowering the priority of CPU-intensive background tasks to allow 'normal' response from a GUI and/or other apps is one of the better uses for altering thread priorities.
Note that lowering the thread priority is not going to have an enormous efect on any resource except CPU, but still worth doing IME.
If you want to carry on using Firefox, Office, VLC etc. while running your app then, yes, lower the priority of the CPU-heavy threads. You should then be able to browse SO, listen to some albums or watch a few films while waiting for your results to eventually come out :)
Note that if you want to change the priority for a thread, you should make sure it's one you've created yourself. It's not good to change the priority on a thread pool thread. This means avoiding the new Task features, unless you're prepared to write a TaskScheduler that doesn't use the thread pool.
Also consider setting the process priority instead, if that suits your scenario. See MSDN for more info. This would affect threads equally.
Edit: Thanks for the additional information. It sounds as though your code is hosted in IIS. From this answer we can confirm that IIS uses the same thread pool as ThreadPool.QueueUserWorkItem - the standard .NET thread pool. Therefore you must not alter the priority of a thread pool thread; these threads belong to IIS.
You could create your own thread. But it seems ill advised to try to host a background operation in IIS like this. You never know when the app pool might be recycled, for example.
It would be better to consider a couple of other options. The best solution for a potentially long running background operation seems to be workflow services. Used in conjunction with AppFabric Server, these are very powerful and sound as though they would handle your situation.
A simpler alternative would be to move the process outside of IIS. Maybe the user's action could mark items for deletion, then a scheduled task outside of IIS could run to perform the slow operation.
I would use ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(MyDeleteMethod), itemsTobeDeleted)
In MyDeleteMethod, you may consider breaking the deletion process in different bulks. In other words, you can specify a max number of rows to be deleted every time you are running the delete method.
If you are worried about number of available connections in the db pool, you can improve the performance by defining a static object (with a timer) and add the itemsTobeDeleted to that list(you need to use lock for sync access). Whenever timer Elapsed event fires, you can perform the bulk delete ( For instance you have 5,000 record and you are going to delete them 500 by 500 ).

Stop application from exiting

I'm working on a Windows application (not WinForms, not Console, not WinService), is just a project with an entry class.
What is the best way, in .NET, to stop an application from exiting the Main method?
I know I can achieve this in console with Console.Read() or I can use EvenWaitHandle.WaitOne() and never call Set().
Is there a better way of doing this?
Thanks for the help in advance.
UPDATE:
This is an overview of the application.
I need to start independent processes (some exe) on demand, containing wcf service. WCF service should listen idefinetly and that is why I need this functionality. The most similar approach I can find is IIS (many w3wp processes running at the same time).
w3svc.exe (IIS windows service) starts many instances of w3wp.exe depending on the number of configured app pools and the requests, it receives.
In my application I want to keep up the processes representing w3wp.exe in the IIS infrastructure, not w3svc. What is the kind of message loop that would keep alive w3wp in .NET?
You can do that in sooo many ways. I personally like this one, as it is very readable and self explanatory:
Process.GetCurrentProcess().WaitForExit();
IIS is a windows service which is why it runs like this. You might look at other options like a single service where you can invoke it via an api and tell it to start another thread or listener. Starting new instances of applications isn't the best option. Typically windows applications have a messagepump, which is a while loop I think...which would prevent it from exiting.
However, you can also follow the example here, which I believe does not close the formless window:
Run Formless Notification User Control?
while(true)
{
// to make it less CPU intensive
Thread.Sleep(1000);
}
Of course, any solution you can think of will not prevent the forceful termination of application by killing its process.
In your update you say that the program is starting several other programs using Process. (It happens to be 'yourself' but that doesn't matter.)
If the program has already done that it doesn't sound like it has any more to do. That process ending won't kill all of the processes it spawned.
You can use the process.WaitForExit() to wait for the processes that you spawn to all exit, rather than just spinning doing nothing, if for some reason you really need to keep the process alive. If there is something that it actually needs to do after spawning the other processes then you'd need to tell us what that is, because if there is something you should be waiting on an event of some sort, which is something you haven't brought up.
Edit: you claim that all the process is doing is "listening". Define that task. If you have a blocking GetNextRequest method then you simply have: while(true){GetNextRequest();}. If it's non blocking, then use use a BlockingCollection<MyRequests> in which the receive method/event hanlder adds a new item to the collection and the main thread had a while loop just like I mentioned before reading from the blocking collection. The point is that you shouldn't ever just sit there and do nothing; you process is doing something, so do that in a while(!done) or while(true) loop. If the method isn't blocking, it's a reasonably well defined problem to solve; just wrap it in a blocking method call.
System.Threading.Thread.Sleep(millisenconds);

Asp.net C#: Check if other threads are running in thread

I'm making a thread that will trigger a change of files in App_GlobalResources, which again will cause the application to recompile, which will abort all other possible running threads.
I need to make this thread that will abort the other threads to wait until all other threads are not running. I have registered all threads in (Hashtable)Application["ThreadList"], but I don't seem to be able to access Application from Threads. Any ideas?
As far as I know ASP.NET doesn't abort currently running worker threads before it recompiles. It starts queuing up requests and waits for the existing requests to finish processing before it restarts AppDomain.
Update:
If your resources change daily than they shouldn't be hard-coded in resx files. Create a new resource provider that loads them from database or external files.

Categories

Resources