[英]How do I wait until one method is finished in C#?
在我的應用程序中,我從另一個來源獲取數據並將這些數據上傳到表中。
所以我寫成,(之前有一些代碼,但我從我想問的開始)
StartProcess();
FirstMonth();
SecondMonth();
ThirdMonth();
private async void StartProcess()
{
try
{
var progress = new Progress<int>(value => { progressBar1.Value = value; });
await System.Threading.Tasks.Task.Run(() => SaveData(progress));
MessageBox.Show("Upload Complete");
}
catch (Exception ex)
{
throw ex;
}
}
private void SaveData(IProgress<int> progress)
{
for (int i = 0; i < dataGridView1.RowCount; i++)//data reading one by one from excel
{
string PartNo = dataGridView1.Rows[i].Cells[0].Value.ToString();
string PartDescription = "";
string PartModel = "";
int AvaQty = int.Parse(dataGridView1.Rows[i].Cells[1].Value.ToString());
DbLoad obj = new DbLoad();
if (obj.UploadStock(PartNo, PartDescription, PartModel, AvaQty))
{
}
else
{
MessageBox.Show("An unexpected error has occurred.Please contact your system administrator");
}
}
MessageBox.Show("Upload Success");
}
這是 FirstMonth 方法
private void FirstMonth()
{
try
{
OracleConnection con = new OracleConnection("OraConnection");
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "Query";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView1.DataSource = dt.DefaultView;
UploadFirstMonth();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
}
private void UploadFirstMonth()
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
string PartNo = dataGridView1.Rows[i].Cells[0].Value.ToString();
int AvaQty = int.Parse(dataGridView1.Rows[i].Cells[1].Value.ToString());
DbLoad obj = new DbLoad();
if (obj.UpdateFirstMonth(PartNo, AvaQty))
{}
else
{
MessageBox.Show("An unexpected error has occurred on First Month Upload.Please contact your system administrator");
}
}
}
通常這有超過 15000 條記錄要上傳到數據庫。 一旦它上傳到數據庫,我想觸發第二個方法FirstMonth來啟動該方法。
但是當前的問題是在完成StartProcess()之前,第二種方法開始處理。 我怎么阻止它? 一旦第一種方法完全完成,我想觸發第二種方法。
您需要在調用FirstMonth()
await StartProcess()
)
這將強制執行在開始FirstMonth
之前等待StartProcess
完成:
await StartProcess();
FirstMonth();
請注意,執行這些的方法需要標記為異步:
public async Task Foo()
{
await StartProcess();
FirstMonth();
}
不過,您可能應該同時await
StartProcess
和FirstMonth
。
您需要將返回類型從 void 更改為 Task 以等待方法完成,因為返回類型為 void 即使您等待調用也不會等待完成,然后您需要使用 await 關鍵字來完成執行。 如下所示。
async someFunction (){
await StartProcess();
FirstMonth();
}
private async Task StartProcess()
{
try
{
var progress = new Progress<int>(value => { progressBar1.Value = value;
});
await System.Threading.Tasks.Task.Run(() => SaveData(progress));
MessageBox.Show("Upload Complete");
}
catch (Exception ex)
{
throw ex;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.