考虑下面的“即发即忘”用例:
调用者从我的方法中请求一些数据。我的方法检查缓存,看看数据是否已经存在。如果不是,它会从源中获取并缓存。调用者不应该在获得结果之前等待缓存发生,并且如果缓存碰巧失败,该方法也不应该阻止调用者获得结果。我今天所拥有的,看起来像这样:
public Foo GetFoo(string fooKey)
{
// look for Foo with fooKey in cache
// if Foo is not found, get Foo with fooKey from source
// and assign it to local variable myFoo
Task cacheTask
= Task.Run
(
() => CacheFoo(myFoo)// fire-and-forget the caching of myFoo
);
return myFoo;
}如果CacheFoo抛出一个异常,它就不会被观察到,最终(在.Net 4.5中)它会被框架吞没。我宁愿自己做最后一次清理异常的尝试,但我不想阻塞当前的线程。那么最好的方法是什么呢?
以下是我尝试过的方法
try
{
...
cacheTask.ContinueWith
(
(e) => {
if (cacheTask.IsFaulted)
{
/* log cacheTask.Exception */;
}
}
, TaskContinuationOptions.OnlyOnFaulted
);
}有没有更好的方法?我是否需要在IsFaulted上使用"if“语句,还是因为我已经指定了"OnlyOnFaulted”而显得多余?
如有任何意见/建议,我们将不胜感激。
发布于 2013-04-12 00:05:50
四件事:
cacheTask;回调中的e也是同样的任务,所以你最好改用它。(然后可以对所有任务使用相同的委托。)https://stackoverflow.com/questions/15953520
复制相似问题