Powershell instance locks up main thread - multithreading

I have a Powershell script with a Windows Forms UI from which I create a new Powershell instance, which in turn starts IE (hidden) and grabs information from a website.
Sometimes the UI locks up and only becomes responsive again after manually killing the hidden IE-process via task manager.
Seemingly IE freezes and this locks up the UI.
Mainly I am trying to understand why this happens. Although it happens every day, so far I was not able to reproduce it by i.e. intentionally creating a new thread which does not respond.
Also I thought a new instance can never lock the main thread anyway, or am I wrong and it is to be expected?
$script:Posh1 = [PowerShell]::Create()
$script:Posh1.AddScript($IEcode)
$script:Posh1.AddParameter("url1",$url1)
$script:Posh1.AddParameter("url2",$url2)
$script:Posh1.BeginInvoke()

Related

PushSharp and Background task

I have been using PushSharp during these last 4 years without too much trouble, and I lately experience problems when sending to more than one device at a time. I was wondering if in a Web environment there is a need to run the PushSharp process in a separate thread in the background or if PushSharp will do that anyway. The reason is that if a web page triggers the push, it will kill the thread as soon as it finishes (although framework 4.5.2 introduced QueueBackgroundWorkItem that will continue to run, but I could not see any difference). On the second hand if the PushSharp task takes too long it will keep the web page busy for an unnecessary time that may be long if there a lot of notifications to send.

How to Use Powershell to Kill threads of a specific processID

well this has been bugging me for a couple of days on and off. I am at a clients site where they have a number of bespoke, written in house, services running on a Windows 2008R2 IIS server. The problem is that a couple of these services keep hanging, they are stuck in a “Stopping” state and the only way to kill them off is to open process explorer and kill the threads. Before anyone says anything about using ‘runas’, or logging on as the local admin, or the service owner, etc we’ve been through all of that.
The problem lies with the executable itselfs. The development team, in another country are going to look at this but it will take 4-5 months minimum, and we’re not certain they’ll get it right then.
I have a Powershell script to check the services on a regular basis which has the ability to ensure the services are running and if not, the force a stop and restart of the service, then it sends an email to confirm the actions. However with these specific services mentioned it can do nothing. They can’t be killed in task manager, taskkill, or process explorer (unless one kills the threads) it just says access denied. It is possible to change the permissions in process explorer and kill it but that’s a lengthier process than killing the threads.
To make things a little more difficult I can’t use the process name as on this server there are two other websites using an exe with the same name, just in a different folder.
What I’m after is a way to find and kill the threads of a processID, which I’ve already obtained via the script I have, so the rest of the script can complete the task of restarting the said service. At the moment this service dies on an inconsistent basis throughout the day and night, and the support guys have to RDP onto the server, open process explorer, find the offending process and kill the threads off then restart the services. A bit too much hassle for these already over worked guys especially if we can get powershell to do it automatically.
Hope someone can help on this. Thanks in advance.
Low level thread handling is likely to require native Win32 API usage. Powershell might help with P/Invoke, but the process is going to be complex. For starters, find out if the following tools can be used to identify the stuck thread. Maybe you can combine this info with some Sysinternals tools like handle.exe to find out what really blocks the thread.
The .Net framework has some tools available via System.Diagnostics.Process namespace. A list for threads for named process is available like so,
$ps = [diagnostics.process]::getProcessesByName("iexplore")
$p = $ps[0]
$p.Threads[0]
Full documentation is in MSDN. There is no method for killing a thread, but this should be kind of starting point for identifying the stuck one.
Another a way is to use WMI to get win32_thread data like so,
$threads = gwmi win32_thread
The output is quite different and some filtering is needed. Some examples are available. Another a WMI solution attempt might be based on Win32_process that has Terminate method.

Processes stuck when more than four instances is created in IIS

Background:
I have a C#.Net (.Net 4.0) Website that calls a engine to grab data from an external database through a vendor executable file that I cannot modify. Whenever user click on a specific button, the webpage will instruct the engine to spawn a few threads, and each thread will spawn a process of the executable (let's called it ABC.exe) to grab the data. The executable will then run, and save the data grabbed into a CSV file on the server. The threads then read the CSV first and consolidate all the data, do some calculation and return to the website.
Problem:
When we deployed the website to IIS 7.5 on a web server (running Window 7, four virtual processors), if we spawn more than 4 threads, the processes will just stuck there.
Test done:
When we run the exact codes using Visual Studio on the same server, no error occurred. All the threads are spawned correctly, and all process is running correctly. This is very weird.
When two user click on the button and both click will spawn 4 threads, the first four threads will work correctly while the second four threads will just stuck there.
When we run the thread with different executables that do not perform any connections, the code works.
In our code, using Task or Thread doesn't make a difference.
We suspect that this might have something to do with the outbound connections allowed to a specific IP in IIS.
Can anyone shed some light on this? Let me know if any further information is required. Thanks!
A couple of thoughts:
Could this be tied to thread pool threads? The CLR tries to prevent the CPU from unnecessary spinning by not handing out (initially anyways) more threads on the thread pool thread than there are processors present. Are there 4 virtual processors present? Thread pool threads should resume eventually, though, so make sure that your threads are really stuck, and not running serial.
I know of a deadlock condition when redirecting standard output in C#. Double check the MSDN article to make sure this is not happening to you.
Additional thoughts:
At this point, it sounds like your ABC.exe is suspect. Since you have Visual Studio on the server, I recommend that you fire up a separate instance of Visual Studio, and attach to one of the ABC.exe processes to see where it is hanging. Also try to run something that you are reasonably sure would exit, e.g. cmd /c dir instead of your ABC.exe.
Edit: 5/29:
I find it hard to believe that IIS would restrict outbound connections this way. Try the following simple downloaded instead of ABC.exe:
class Program
{
public static void Main(string[] args)
{
using (var reader = new System.IO.StreamReader(
System.Net.HttpWebRequest.Create("http://www.google.com")
.GetResponse().GetResponseStream()))
{
System.Console.WriteLine(reader.ReadToEnd());
}
}
}

Delphi - Creating a control that runs in its own process

HI
I have a control that accesses a database using proprietary datasets. The database is an old ISAM bases database.
The control uses a background thread to query the database using the proprietary datasets.
A form will have several of these controls on it, each using their own thread to access the data as they all need to load simultaneously.
The proprietary datasets handle concurrency by displaying a VCL TForm notifying the user that the table being opened is locked by another user and that the dataset is waiting for the lock to be released.
The form has a cancel button on it which lets the user cancel the lock wait.
The problem:
When using the proprietary datasets from within a thread, the application will crash, hang or give some error if the lock wait form it displayed. I suspect this is to do with the VCL not being thread safe.
I have solved the issue by synchronizing Dataset.Open however this holds up the main thread until the dataset.open returns, which can take a considerable amount of time depending on the complexity of the query.
I have displayed a modal progress bar which lets to user know that something it happening but I don't like this idea as the user will be sitting waiting for the progress bar to complete.
The proprietary dataset code is compiled into the main application, i.e. its not stored in a separate DLL. We are not allowed to change how the locking works or whether a form is displayed or not at this stage of the development process as we are too close to release.
Ideally I would like to have Dataset.open run in the controls thread as well instead of having the use the main thread, however this doesn't seem likely to work.
Can anyone else suggest a work around? please.
Fibers won't help you one bit, because they are in the Windows API solely to help ease porting old code that was written with cooperative multitasking in mind. Fibers are basically a form of co-routines, they all execute in the same process, have their own stack space, and the switching between them is controlled by the user code, not by the OS. That means that the switching between them can be made to occur only at times that are safe, so no synchronization issues. OTOH that means that only one fiber can be running within one thread at the same time, so using fibers with blocking code has the same characteristics as calling blocking code from within one thread - the application becomes unresponsive.
You could use fibers together with multiple threads, but that can be dangerous and doesn't bring any benefit over using threads alone.
I have used fibers successfully within VCL applications, but only for specific purposes. Forget about them if you want to deal with potentially blocking code.
As for your problem - you should make a control that is used for display purposes only, and which uses the standard inter-process communication mechanisms to exchange data with another process that accesses your database.
COM objects can run in out-of-process mode. May be in delphi it will be a bit easier to use them, then another IPC mechanisms.

Multithread Form Application (.NET 4.0)

I'm currently working on a solution that has two projects, a console and a form application. The console application is the main entry point to my application, and from the console the user would run the form application.
The problem is, when the user boots the form application the rest of the business logic (from the console app) won't run until the form is closed. My first thought was to use a background worker for the form, but the business logic in the form project already uses a background worker (and I only have two CPUs...). Perhaps this could be my ignorance for multithreading, but is there a way to do this?
Any thoughts are much appreciated!
Cheers
Well, this is pretty unusual. In general, it doesn't make a lot of sense to provide the user with a nice GUI and still leave a console window up and interactive.
But yes, calling Application.Run() or Form.ShowDialog() is going to block the thread. It has to, the message loop needs to be running to keep the GUI alive. If you do this, be sure to put the [STAThread] attribute on the Main() method.
The only other decent alternative is to start a thread. This isn't a problem, a UI thread doesn't burn any CPU cycles. Code only ever runs when the user does something, it's otherwise idle 99% of the time. Be sure to call the thread's SetApartmentState() method before you start it, STA is required.

Resources