【发布时间】:2011-05-31 07:17:00
【问题描述】:
所以我正在尝试使用 .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(我的实体框架数据上下文成员)、this.Logger(记录器成员)和线程(在记录器调用中使用)。通常在 QueueUserWorkItem() 天,我认为这些需要作为状态对象的一部分传递给委托。关闭会不会让我不再需要这样做?
另一个问题是该例程所在的类型实现了 IDisposable,因此位于 using 语句中。所以如果我做类似...
using (var bl = new ThreadBL()) {
t = bl.ViewThread(threadId);
}
...我要在 dispose() 调用和 TPL 开始调用我的 lambda 之间进行竞争吗?
目前我看到上下文将数据保存回我的数据库,但没有记录 - 也没有例外。这可能是我的配置问题,但这段代码感觉很奇怪。我不想在其他线程中有未处理的异常。欢迎任何意见!
【问题讨论】:
标签: multithreading c#-4.0 closures task-parallel-library