I have a multi-threaded C# console application that uses WMI
(System.Management namespace) to make RPC calls to several servers (600+ )
and returns ScheduledJobs. The section of my code that performs the query
is contained in a delegate function that I execute via a second thread. On 1
or 2 of the 600+ servers the query hangs. I've tried to use Thread.Join()
coupled with a Thread.Abort() but this does not kill the thread.
Based on other post I've read this is a common occurrence and the only way
to kill this thread is to use TerminateThread() located in the Kernel32.dll.
I'm not really sure how to call this unmanaged code. Also TerminateThread()
requires the thread's handle and I'm not sure how to obtain this in .NET.
I've made a "best guess" at the code but it doesn't work. See sample below.
Can anyone give me a code sample of how this can be done? This is my first
multi-threaded application and I'm pretty much a newbie to unmanaged code.
// This class allows me to pass a server name to the function
// and still call it as a delegate.
public class Parcer
{
public int ThreadID;
private string Server;
public DataSet ds;
public Parcer(string Server)
{
this.Server = Server;
}
public void ParceJobs()
{
ThreadID = AppDomain.GetCurrentThreadId();
IntelJobReader JobReader = new IntelJobReader(); //Instanciate the
JobReader object. This is a class I wrote that make the WMI calls and
returns a DataSet.
DataSet JobSchedules = ( DataSet ) ( JobReader.GetSvrJobs(Server) );
this.ds = JobSchedules;
}
}
// This is my best guess at the unmanaged code. It runs without error but
does not terminate the thread.
public class Win32
{
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern int TerminateThread(int hThread);
}
// Excerpt from my Conseole App's Main code:
Parcer SchJobs = new Parcer(Server);
Thread JobTimeout = new Thread(new ThreadStart(SchJobs.ParceJobs));
JobTimeout.Start();
JobTimeout.Join(10000);
if (!JobTimeout.Join(10000))
{
JobTimeout.Abort(); // This will not terminate the thread
Win32.TerminateThread(AppDomain.GetCurrentThreadId ());
Console.WriteLine("The thread timed out no change will be made to the
DB");
}
Thanks,
Bryan