关于异步任务和处置 [英] About Async Tasks and Disposal

查看:168
本文介绍了关于异步任务和处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主窗口我有一个可用于打开按钮过程(本机调用OpenProcess 调用),并执行它的记忆一些检查,但呼吁点击是异步的:

In my MainWindow I have a button that can be used to open a Process (native OpenProcess call) and perform some checks on it's memory, but the method called on Click is asynchronous:

<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.
}

现在,让我们来看看$ a的视图模型部分C $ C ...

Now, let's see the ViewModel portion of code...

// 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;
}

现在......这里来的问题。当用户关闭应用程序,如果进程打开时,我一定要正确地关闭其句柄。所以在我的主窗口我有以下的code:

Now... here comes the problem. When the user closes the application, if a Process is opened, I must properly close its handle. So in my MainWindow I have the following code:

protected override void OnClosing(CancelEventArgs e)
{
    m_ViewModel.Detach();
    base.OnClosing(e);
}

在我的视图模型我有以下的code:

And in my ViewModel I have the following code:

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;
    }
}

附加()方法可能需要很长的时间,超过2分钟的时候。我需要找到以下问题的一个解决方案:

The Attach() method can take very long time, more than 2 minutes sometimes. I need to find a solution for the following issues:

  • 如果用户关闭,而应用程序连接()方法是在运行之前 memoryProcess 保存到私有变量,该进程手柄不会被关闭。
  • 如果我的MemoryProcess实例保存到私有变量只是在开始的附加()的方法,没有为用户获得风险的NullReferenceException 如果他关闭应用程序,而附加()方法处理的foreach循环。
  • 我绝对不想让用户等待附加()办法让他关闭应用程序之前完成。这是可怕的。
  • If the user closes the application while Attach() method is running and before memoryProcess is saved to the private variable, the Process handle will not be closed.
  • If I save the MemoryProcess instance to the private variable just at the beginning of the Attach() method, there is a risk for the user to get a NullReferenceException if he closes the application while the Attach() method is processing its foreach loop.
  • I absolutely don't want to make the user wait for Attach() method to complete before letting him close the application. That's horrible.

我怎样才能做到这一点?

How can I do this?

推荐答案

海事组织,如果你不明确而具体针对创建单独的独立式/独立的过程一样,例如,通过:

IMO, if you do not explicitly and specifically target to create separate detached/independent processes like, for example, through:

  • 使用PInvoke.CreateProcess
  • 使用

  • using PInvoke.CreateProcess
  • using

(new System.Management.ManagementClass("Win32_ProcessStartup"))
.Properties["CreateFlags"].Value = 8;

  • 或维持子进程在应用程序关闭活着通过单独的shell脚本或剩余程序结束后,运行其他程序启动他们。

  • or maintaining child process alive upon app closing by launching them through separate shell scripts or other processes remaining to run after app closing;

    或发现已经运行单独处理,你不需要和的可能不应该关闭或处置由应用程序进程生成的。视窗(operting系统)将关闭所有未关闭的病死猪过程催生。

    or finding already run independently processes, you don't need to and probably should not "close" or dispose spawned by app processes. Windows (operting system) will close any unclosed spawned by app processes.

    另外,我认为这是不可能执行任何code在应用程序一旦启动退出或关闭。

    Also, I believe that it is impossible to execute any code in an application once it has started exiting or being closed.

    PS(题外话评论):
    我甚至不知道你关闭(<一href="http://stackoverflow.com/questions/673031/process-close-is-not-terminating-created-process-c">really应该杀)或处置您的code你的流程...

    PS (off-topic comment):
    I do not even see that you close (really one should kill) or dispose your processes in your code...

    这篇关于关于异步任务和处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆