总而言之,我最近使用多线程的大型应用程序存在并发问题。问题出在可以运行批处理作业的脚本处理器中
public async Task<Result> ProcessScriptAsync(
CancellationTokenSource cancelSource,
TaskScheduler uiScheduler)
{
...
// Get instance of active workbook on UI thread.
IWorkbook workbook = this.workbookView.ActiveWorkbook;
while (notFinished)
{
...
Task<bool> runScriptAsyncTask = null;
runScriptAsyncTask = Task.Factory.StartNew<bool>(() =>
{
return RunScript(ref workbook);
}, this.token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
// Some cancellation support here...
// Run core asynchroniously.
try
{
bGenerationSuccess = await runScriptAsyncTask;
}
catch (OperationCanceledException)
{
// Handle cancellation.
}
finally
{
// Clean up.
}
}
...
}
当您考虑该RunScript
方法时,我的问题就来了。传入的对象RunScript
不是线程安全的,而是在 UI 线程上创建的。因此,我必须在RunScript
方法内创建该对象的“深层副本”......
private bool RunScript(ref IWorkbook workbook)
{
...
// Get a new 'shadow' workbook with which to operate on from a background thread.
IWorkbook shadowWorkbook;
if (File.Exists(workbook.FullName))
{
// This opens a workbook from disk. The Factory.GetWorkbook method is thread safe.
shadowWorkbook = SpreadsheetGear.Factory.GetWorkbook(workbook.FullName); // (##)
}
else
throw new FileNotFoundException(
"The current workbook is not saved to disk. This is a requirement. " +
"To facilitate multi-threading!");
// Do hard work here...
shadowWorkbook.WorkbookSet.GetLock();
try
{
// Do work and add worksheets to shadowWorkbook.
}
finally
{
// Reassign the UI workbook object to our new shadowWorkbook which
// has been worked on. This is fine to do as not work is actually being
// done on workbook.
workbook = shadowWorkbook;
shadowWorkbook.WorkbookSet.ReleaseLock();
}
}
我的问题在 (##) 标记的行上。每次执行都是从磁盘RunScript
创建一个新的。shadowWorkbook
这样做的问题是在其中创建了一些工作表,随后在处理结束时将shadowWorkbook
其复制回。workbook
但是,每次执行时,RunScript
我都会从磁盘中获取工作簿,该工作簿没有在最后一个循环中生成的新工作表。
我已经研究过制作shadowWorkbook
一个全局对象,但它是在 UI 线程上创建的,因此随后无法从我的后台操作中使用。解决此问题的一种方法是在每个工作表创建后将工作簿保存到磁盘,但是有很多创建,这将是昂贵的。
有没有办法使shadowWorkbook
全局和线程安全,使我能够持久更改IWorkbook
跨线程调用?
谢谢你的时间。