开发者

.NET TPL lambdas and closures - will this code work

So I'm trying to use the TPL features in .NET 4.0 and have some code like this (don't laugh):

/// <summary>Fetches a thread along with its posts.  Increments the thread viewed counter.</summary>
public Thread ViewThread(int threadId)
{
   // Get the thread along with the posts
   Thread thread = this.Context.Threads.Include(t => t.Posts)
       .FirstOrDefault(t => t.ThreadID == threadId);

   // Increment viewed counter
   thread.NumViews++;
   Task.Factory.StartNew(() =>
   {
       try {
           this.Context.SaveChanges();
       }
       catch (Exception ex) {
           this.Logger.Error("Error viewing thread " + thread.Title, ex);
       }

       this.Logger.DebugFormat(@"Thread ""{0}"" viewed and incremented.", thread.Title);
   });

   return thread;
}

So my immediate concerns with the lambda are this.Context (my entity framework datacontext member), this.Logger (logger member) and thread (used in the logger call). Normally in the QueueUserWorkItem() days, I would think these would need to be passed into the delegate as part of a state object. Are closures going to be bail me out of needing to do that?

Another issue is that the type that this routine is in implements IDisposable and thus is in a using statement. So if I do something like...

using (var bl = new ThreadBL()) {
            t = bl.ViewThread(threadId);
        }
开发者_运维技巧

... am I going to create a race between a dispose() call and the TPL getting around to invoking my lambda?

Currently I'm seeing the context save the data back to my database but no logging - no exceptions either. This could be a configuration thing on my part but something about this code feels odd. I don't want to have unhandled exceptions in other threads. Any input is welcome!


As for your question on closures, yes this is exactly what closures are about. You don't worry about passing state, instead it is captured for you from any outer context and copied onto a compiler supplied class which is also where the closure method will be defined. The compiler does a lot of magic here to make you're life simple. If you want to understand more I highly recommend picking up Jon Skeet's C# in Depth. The chapter on closures is actually available here.

As for your specific implementation, it will not work mainly for the exact problem you mentioned: the Task will be scheduled at the end of ViewThread, but potentially not execute before your ThreadBL instance is disposed of.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜