我已经在使用 backgroundworker.RunAsyn() 在单独的线程上运行我的代码。但是,我遇到了代码在上一行完成之前迭代到下一行的部分。我应该创建一个单独的 backgroundworker 来处理吗?或者我应该使用 Application.Wait() 或 Thread.Sleep() 我不确定延迟的时间量,我不想让我的程序只是坐着等待额外的不需要的时间,所以我不确定该走哪条路。这是麻烦制造者的片段。
public Form_Main()
{
InitializeComponent();
backgroundworker1.WorkerReportsProgress = true;
backgroundworker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1_ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void btnOpenRefreshSave_Click()
{
backgroundWorker1_RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Excel.Application exApp;
Excel._Workbook exBook;
Excel._Worksheet exSheet;
exBook = (Excel._Workbook)(exApp.WOrkbooks.Open("C:\\Book1.xlsx"));
exSheet = (Excel._Worksheet)(exBook.ActiveSheet);
//This is the line of code that often times takes a while
exBook.RefreshAll();
//end of trouble line
exBook.SaveAs("C:\\Updated_Book1.xlsx");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
请您参考如下方法:
关于在这里做什么,我想到了一些事情。你可以尝试使用类似于下面的东西
if (Application.CalculationState === xlDone Then
everything is finished calculating[enter link description here][1]
另一种选择是(正如其他人所建议的那样)更改背景刷新属性。快速扫描工作簿可以以编程方式为您更改它
foreach (Wrksheet ws in workbook.wss)
{
foreach (QueryTable table in ws.QueryTables)
table.BackgroundQuery = false;
}
workbook.RefreshAll();
