在我的MainWindow中,我有一个按钮,可以用来打开一个Process (原生OpenProcess调用)并对它的内存执行一些检查,但是在Click上调用的方法是异步的:
<Button Content="Attach" Click="OnClickAttach"/>
private async void OnClickAttach(Object sender, RoutedEventArgs e)
{
AttachmentResult result = await m_ViewModel.Attach();
switch (result)
// Different MessageBox depending on the result.
}现在,让我们看看代码的ViewModel部分..。
// MemoryProcess class is just a wrapper for Process' handle and memory regions.
private MemoryProcess m_MemoryProcess;
public async Task<AttachmentResult> Attach()
{
AttachmentResult result = AttachmentResult.Success;
MemoryProcess memoryProcess = NativeMethods.OpenProcess(m_SelectedBrowserInstance.Process);
if (memoryProcess == null)
result = AttachmentResult.FailProcessNotOpened;
else
{
Boolean check1 = false;
Boolean check2 = false;
foreach (MemoryRegion region in memoryProcess)
{
// I perform checks on Process' memory regions and I eventually change the value of check1 or check2...
await Task.Delay(1);
}
if (!check1 && !check2)
{
NativeMethods.CloseHandle(memoryProcess.Handle);
result = AttachmentResult.FailProcessNotValid;
}
else
{
// I keep the Process opened for further use. I save it to a private variable.
m_MemoryProcess = memoryProcess;
m_MemoryProcess.Check1 = check1;
m_MemoryProcess.Check2 = check2;
}
}
return result;
}现在..。问题来了。当用户关闭应用程序时,如果打开了一个Process,我必须正确关闭它的句柄。因此,在我的MainWindow中,我有以下代码:
protected override void OnClosing(CancelEventArgs e)
{
m_ViewModel.Detach();
base.OnClosing(e);
}在我的ViewModel中,我有以下代码:
public void Detach()
{
if (m_MemoryProcess != null)
{
if (m_MemoryProcess.Check1)
// Do something...
if (m_MemoryProcess.Check2)
// Do something...
NativeMethods.CloseHandle(m_MemoryProcess.Handle);
m_MemoryProcess = null;
}
}Attach()方法可能需要很长的时间,有时超过2分钟。我需要找到解决以下问题的办法:
Attach()方法时关闭应用程序,并且在memoryProcess保存到私有变量之前,Process句柄将不会关闭。Attach()实例保存到私有变量,那么如果用户在Attach()方法处理它的foreach循环时关闭应用程序,就有可能获得NullReferenceException。Attach()方法完成后才让他关闭应用程序。太可怕了。我该怎么做?
发布于 2013-05-15 06:04:03
海事组织,如果您没有明确和明确地针对创建独立/独立的进程,例如,通过:
CreateRemoteThread在另一个独立进程中创建一个新线程或者发现已经独立运行的进程,您不需要和可能不应该“关闭”或处理由应用程序进程生成的。Windows (操作系统)将关闭应用程序进程产生的任何未关闭的操作。
而且,我认为,一旦应用程序开始退出或关闭,就不可能在应用程序中执行任何代码。
PS (非主题评论):
我甚至没有看到您关闭(真的应该杀了人)或在您的代码中释放您的进程。
https://stackoverflow.com/questions/16551857
复制相似问题