我已經使用backgroundworker.RunAsyn()
在單獨的線程上運行我的代碼。不過,我在上一行完成之前觸及代碼迭代到下一行的部分。我應該創建一個單獨的backgroundworker
來處理?或者我應該使用Application.Wait()
還是Thread.Sleep()
我不確定拖延的時間,我寧願不讓我的程序坐在等待額外的不需要的時間,所以我不確定要採取哪條路線。這是一個麻煩製造者的片段。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)
{
}
你是什麼意思的「代碼迭代到前一行完成之前的下一行」? –
@SriramSakthivel它將在刷新操作有時間完成之前保存工作簿。 –
請參考[this](http://stackoverflow.com/questions/8925403/excel-vba-refresh-wait)和[this](http://stackoverflow.com/questions/18788384/wait-for-workbook-refreshall -c) –