المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Using Semaphore for multiple threads....



C# Programming
02-13-2010, 05:31 PM
Let me first start with what I am trying to accomplish and what I have.

I created a computer management console for active directory. You launch, it gets all computer objects from AD. When you click the computer object, some panels become visible and thre are 3 listbviews. One for Installed Applications, One for Services, and one for Hard drive information. All of that information is retrieved by WMI.

So the way I have it is when you click a computer object, it attempts to contact the computer using seperate threads for each thing (applications, services, hd info).

I have something like this:

// Threading for getting WMI information
Thread m_workerThread1;
Thread m_workerThread2;
Thread m_workerThread3;
Semaphore resourceLock;

When you click comp:

if (m_workerThread1 != null && m_workerThread1.IsAlive)
m_workerThread1.Abort();

if (m_workerThread2 != null && m_workerThread2.IsAlive)
m_workerThread2.Abort();

if (m_workerThread3 != null && m_workerThread3.IsAlive)
m_workerThread3.Abort();

lstServices.BeginUpdate();
lstServices.Items.Clear();

m_workerThread1 = new Thread(new ParameterizedThreadStart(GetRunningServices));
m_workerThread1.IsBackground = true;
m_workerThread1.Start(comp.DnsHostName);

lstApplications.BeginUpdate();
lstApplications.Items.Clear();

m_workerThread2 = new Thread(new ParameterizedThreadStart(GetInstalledApps));
m_workerThread2.IsBackground = true;
m_workerThread2.Start(comp.DnsHostName);

lstDiskDrives.BeginUpdate();
lstDiskDrives.Items.Clear();

m_workerThread3 = new Thread(new ParameterizedThreadStart(GetCompInfo));
m_workerThread3.IsBackground = true;
m_workerThread3.Start(comp.DnsHostName);

And under each method (you see I am calling three different ones) I am using the resourceLock.WaitOne(); and under a try catch finally (in the finally) I am releasing it.

You might be wondering why I call abort. This is because I really couldn't think of a better way to abort the current operation if the user clicks another computer. Having it wait until its done before letting the user choose another computer really isn't an option (because WMI can take a while sometimes).

My problem is if you close the form while these threads are running. Right now I forgot to include anything for it and it causes teh app to crash.

Is there a good way to abort these and then close? Like without displaying a message for the user to wait and try again until it aborts? What is the "best practice" for handling something like this? Or did I just mess the whole system up the way I did it?