0

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;
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
  • Do you have Resharper? – Scott Chamberlain Dec 17 '15 at 20:44
  • see this post http://stackoverflow.com/questions/16566547/do-using-statements-and-await-keywords-play-nicely-in-c-sharp – Thomas Dec 17 '15 at 20:44
  • @Scott Chamberlain Yes, I have resharper installed – Bradley Uffner Dec 17 '15 at 20:45
  • 1
    It is perfectly safe, it is a false positive from resharper's engine. See [my answer](http://stackoverflow.com/a/17620526/80274) in the linked duplicate for instructions on how to "help" it know it is safe to do what you are doing. – Scott Chamberlain Dec 17 '15 at 20:45
  • Ahh, thank you. I ran across that question while researching before posting this question, but I couldn't tell if it was the same situation I had or not due to my unfamiliarity with async/await. – Bradley Uffner Dec 17 '15 at 20:50

0 Answers0