Hi All,
I am working on a very simple taskmanager, which lists all running processes (in a listbox) and let's a user kill a process with a button.
When a process is killed, it should "refresh" the list of process and the recently killed process should ofcourse not be there anymore.
The problem:
I'm trying to "refresh" the listbox with listBox.Items.Clear(); after the process has ben killed , but when the getproc() method is called again, the recently killed process is still in the list.
Does anyone have any suggestions ?
Thanks !
The code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Process[] procs;
private void getproc()
{
procs = Process.GetProcesses();
{
listBox.Items.Clear();
{
foreach (Process proc in procs)
listBox.Items.Add(proc.ProcessName);
}
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
procs[listBox.SelectedIndex].Kill();
getproc();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
getproc();
}
}
}
Loading
Zoran HorvatPosted Nov 16, 2010, 7:54 AM
Refreshing processes immediately after calling Kill may be too early - maybe give Kill some time to execute in the background? One way to do that is to wait for process to exit using Process.WaitForExit method with some wait time specified, e.g. 1-2 seconds. Note that Kill operates asynchronously. It gives OS instruction to terminate process without sending it message to exit gracefully (e.g. message to close main window). That instruction is not executed immediately, but may take some time depending on what resources this process is using and other factors.
You can use other tools to compare processes list with your tool's output, like PsList, or conventional Task Manager.
minaajPosted Nov 16, 2010, 8:26 AM
I used a Thread.Sleep(1000) after killing the process which solves the problem. Thanks !