title: Hangfire BackgroundJob.Enqueue and method serialization
body: <p>With hangfire we can do something like:</p>
  
  <pre><code>public MyClass
  {
      public void RunJob()
      {
          SomeClass x = new SomeClass();
          x.SomeProperty = "Test";
          Hangfire.BackgroundJob.Enqueue(() =&gt; x.SomeMethod());
      }
  }
  </code></pre>
  
  <p>Imagine that <code>SomeMethod</code> is not static, and depends upon the value of SomeClass.SomeProperty. If <code>SomeMethod</code> is not static, how can this work? Object <code>x</code> will go out of scope two lines later. Does Hangfire increase the reference count to object <code>x</code> and the garbage collector doesn't clean up the object until Hangfire is done with it?</p>
  
  <p>Further, imagine if <code>SomeClass</code> implements IDisposable and <code>SomeMethod</code> depends upon resources cleaned up by Dispose:</p>
  
  <pre><code>public MyClass
  {
      public void RunJob()
      {
          using (SomeClass x = new SomeClass())
          {
              x.SomeProperty = "Test";
              Hangfire.BackgroundJob.Enqueue(() =&gt; x.SomeMethod());
          }
      }
  }
  </code></pre>
  
  <p>In this case x.Dispose would likely be called before the job is run. Does this cause a bug?</p>
  
  <p>In testing I can see that private member SomeClass._disposed is set to true following the using statement, but when Hangfire calls <code>SomeMethod</code> seconds later, SomeClass._disposed is set to false! How does this black magic happen!?</p>
  
  <p><strong>Observations</strong></p>
  
  <p>I modified the class to include:</p>
  
  <pre><code>public MyClass
  {
      public static int LastId = 0;
      private static int Id = 0;
  
      public MyClass()
      {
          Id = ++LastId;
      }
  
      public void RunJob()
      {
          using (SomeClass x = new SomeClass())
          {
              x.SomeProperty = "Test";
              Hangfire.BackgroundJob.Enqueue(() =&gt; x.SomeMethod());
          }
      }
  }
  </code></pre>
  
  <p>... using this I can observe that the <code>Id</code> of the class used by Hangfire is not the same instance used in my first example. So I assume Enqueue makes a copy of object x, or maybe the () => operator does.</p>