title: Is it safe for Task.Run() to access Method scope variables?
body: <p>Is the following guaranteed to print &quot;Success,&quot; or is it possible garbage collection can eat the &quot;dummyValue&quot; object since TaskTest() ends long before the task it returns can finish?</p>
  <pre><code>public class DummyValueClass
  {
      public string Value { get; private set; }
  
      public DummyValueClass(string value)
      {
          Value = value;
      }
  }
  
  public class ScopeTest
  {
      public Task&lt;string&gt; TaskTest()
      {
          var dummyValue = new DummyValueClass(&quot;Success&quot;);
  
          return Task.Run(() =&gt;
          {
              Thread.Sleep(10000);
              return dummyValue?.Value;
          });
      }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine(&quot;Beginning Test&quot;);
          var scopeTester = new ScopeTest();
          var task = scopeTester.TaskTest();
          Console.WriteLine(task.Result);
      }
  }
  </code></pre>