.NET TPL lambda和闭包-此代码将起作用
|
因此,我试图在.NET 4.0中使用TPL功能,并使用如下代码(不要笑):
/// <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;
}
因此,我对lambda的直接关注是this.Context(我的实体框架datacontext成员),this.Logger(logger成员)和线程(在logger调用中使用)。通常,在QueueUserWorkItem()天内,我认为这些将需要作为状态对象的一部分传递给委托。封闭会否使我不必这样做呢?
另一个问题是此例程所在的类型实现IDisposable,因此位于using语句中。所以,如果我做类似...
using (var bl = new ThreadBL()) {
t = bl.ViewThread(threadId);
}
...我是否要在dispose()调用和TPL调用我的lambda之间创建竞赛?
目前,我看到上下文将数据保存回我的数据库,但是没有日志记录-也不例外。就我而言,这可能是配置问题,但有关此代码的某些事情感觉很奇怪。我不想在其他线程中有未处理的异常。欢迎任何输入!
没有找到相关结果
已邀请:
1 个回复
绵扇寸访
的末尾,但可能在处置
实例之前不会执行。