我有以下代码片段,它创建一个进程,附加到作业对象,最后一个块,处理作业对象然后处理进程。我仍然遇到CA2000:DisposeObjectsBeforeLosingScope代码分析错误。我有什么想法可以摆脱这个代码分析错误吗?
Process process = null;
JobObject processGroupLimitJobMemory = null;
try
{
// Code to create process,
// initialize job object and attach process to job object
// Code to create process and attach to job object
processGroupLimitJobMemory = new JobObject();
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
WorkingDirectory = @"c:\Windows\System32",
FileName = "notepad.exe",
Arguments = null,
UseShellExecute = false
};
process.Start();
processGroupLimitJobMemory.AttachProcess(process);
return;
}
catch (InvalidOperationException e)
{
return;
}
finally
{
if(processGroupLimitJobMemory != null)
{
processGroupLimitJobMemory.Dispose();
}
if (process != null)
{
try
{
if (!process.HasExited)
{
Utilities.KillProcessTree(process);
}
}
catch (InvalidOperationException e)
{
// Trace
}
catch (ExternalException e)
{
// Trace
}
finally
{
process.Dispose();
}
}
答案 0 :(得分:1)
通过第一个只要有可能,我倾向于使用{{围绕catch (InvalidOperationException e)
异常处理程序有一个代码分支,它不会处理processGroupLimitJobMemory
。IDisposables
,因为它简化了我们的嵌套和分支处置方案 - 相邻using
s也可以using
synctatic sugar以避免嵌套。我相信process
和processGroupLimitJobMemory
都可以放在using
中,代码重新格式化如下:
try
{
using (var processGroupLimitJobMemory = new JobObject())
using (var process = new Process())
{
try
{
process.StartInfo = new ProcessStartInfo
{
WorkingDirectory = @"c:\Windows\System32",
FileName = "notepad.exe",
Arguments = null,// R# indicates this is a not null attribute
UseShellExecute = false
};
process.Start();
processGroupLimitJobMemory.AttachProcess(process);
}
finally
{
if (!process.HasExited)
{
try
{
Utilities.KillProcessTree(process);
}
catch (InvalidOperationException e)
{
// Trace
}
catch (ExternalException e)
{
// Trace
}
}
}
}
}
catch (InvalidOperationException e)
{
return;
}
答案 1 :(得分:1)
在最终工作的
中处理JobObject之前移动处理的处理 finally
{
if (process != null)
{
try
{
if (!process.HasExited)
{
Utilities.KillProcessTree(process);
}
}
catch (InvalidOperationException e)
{
// Trace
}
catch (ExternalException e)
{
// Trace
}
finally
{
process.Dispose();
}
}
if(processGroupLimitJobMemory != null)
{
processGroupLimitJobMemory.Dispose();
}
}