In the following block of code I am receiving a warning on the proc
variable, on the 3 lines inside the Task.Run
. The warning states "Access to disposed closure". I believe that this code is actually safe; that the await
on the task will prevent the using
block from exiting and disposing proc
. The code seems to work the way I expect, there are no errors at run time. However, I am a bit new to the Async / Await pattern and want to make sure that there isn't some subtle race condition, or something else that I am overlooking, that the warning is trying to alert me to.
Is the code inside the Task
safe the way I have written it?
public async Task<int> BuildInstaller()
{
var paths = new PathInfo();
PrepareWorkingDirectory(paths);
using (var proc = new Process())
{
proc.StartInfo.FileName = paths.MsBuildPath;
proc.StartInfo.Arguments = $"{paths.SolutionDirectory}\\FoodSafety.Installer.sln /t:Rebuild /p:Configuration=SingleImage";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.OutputDataReceived += (sender, e) =>
{
Application.Current.Dispatcher.BeginInvoke(new Action(() => { BuildOutput.Add(e.Data); }), null);
};
await Task.Run(() =>
{
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
});
return proc.ExitCode;
}
}