在我们的代码库中,我们有很多其他方法,它们基本上只是管道,看起来像这样:
public void Execute()
{
_performanceLogger.Log("Start");
var chunks = GetChunksToWorkOn();
Parallel.ForEach(chunks , chunk =>
{
using (var container = ObjectFactory.Container.GetNestedContainer())
{
using (var unitOfWork = new UnitOfWork())
{
container.GetInstance<Worker>().Execute(chunk);
unitOfWork.Commit();
}
}
});
_performanceLogger.Log("Done");
}
我正在考虑创建一个模板方法来替换这些调用,如下所示:
public interface IProcessInParallel
{
void Execute<T>(Func<IEnumerable<IEnumerable<object>>> funcToRetrieveChunksOfWorkForEachParallelProcess) where T : IProcessInParallelTask;
}
public interface IProcessInParallelTask
{
void DoWork(IEnumerable<object> objects);
}
public class ProcessInParallel : IProcessInParallel
{
private readonly IPerformanceLogger _performanceLogger;
public ProcessInParallel(IPerformanceLogger performanceLogger)
{
_performanceLogger = performanceLogger;
}
public void Execute<T>(Func<IEnumerable<IEnumerable<object>>> funcToRetrieveChunksOfWorkForEachParallelProcess) where T : IProcessInParallelTask
{
_performanceLogger.Log("Start");
var chunks = funcToRetrieveChunksOfWorkForEachParallelProcess.Invoke();
Parallel.ForEach(chunks, chunk =>
{
using (var container = ObjectFactory.Container.GetNestedContainer())
{
using (var unitOfWork = new UnitOfWork())
{
container.GetInstance<T>().DoWork(chunk);
unitOfWork.Commit();
}
}
});
_performanceLogger.Log("Done");
}
}
这种方法的唯一问题是它使用了对象......这是丑陋的不安全并导致演员表。
我正在浏览我的模式书,但还没有找到正确的解决方案。
有什么建议么?