WaitForSingleObject(Handle, Timeout)
Recently I was working on a problem where I had to create new process on a click of a button. With this, I needed some callback or signal when this new process terminates. This new process was launched on a new thread. I looked into the Thread Class but there was no out of box functionality to achieve this. So I end up writing this code.
Here is the PInvoke Declaration
[DllImport("Kernel32.dll", CharSet=CharSet.Unicode,SetLastError=true)]
static extern uint WaitForSingleObject(
IntPtr HANDLE,
uint Timeout);
Creating a new Thread to start our process…
newThread = new Thread(new ThreadStart(StartNewApplication));
newThread.Name = "ClientApplication";
newThread.Start();
private void StartNewApplication()
{
//Declarations...
const uint INFINITE = 0xFFFFFFFF;
uint returnValue;
int error;
//Creating a new process
Process pr = new Process();
pr.StartInfo.FileName="RemotingServer.exe";
pr.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
pr.Start();
//Using WaitForSingleObject to wait till the threads give a
//signal. As we want to get signaled when the thread gets
//terminated, we set timeout time as "Infinite".
IntPtr HANDLE = pr.Handle;
returnValue = WaitForSingleObject(HANDLE,INFINITE);
if (returnValue == 0xFFFFFFFF)
{
//Getting error code...
error = Marshal.GetLastWin32Error();
}
else
{
//Code which we want to execute after the thread has been terminated
}
}



3 Comments:
Check out the WaitForExit() method on the Process class. It will do exactly what you want without having to pinvoke (WaitForExit actually uses WaitForSingleObject internally).
Hello, Just wandering the blogosphere and happened on your blog. I like the way how you have put it all together. I'll be coming back again.
Regards,
AIU Degree Online
I found this site using [url=http://google.com]google.com[/url] And i want to thank you for your work. You have done really very good site. Great work, great site! Thank you!
Sorry for offtopic
Post a Comment
<< Home