简体   繁体   English

如何等到 C# 中的一种方法完成?

[英]How do I wait until one method is finished in C#?

In my application I'm getting data from another source and uploading those data to the tables.在我的应用程序中,我从另一个来源获取数据并将这些数据上传到表中。

So I wrote it as,(there are some codes before that, but I start with what I want to ask)所以我写成,(之前有一些代码,但我从我想问的开始)

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");
}

This is the FirstMonth Method这是 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");
   }
  }
}

Normally this has more than 15000 records to be upload to the database.通常这有超过 15000 条记录要上传到数据库。 Once it uploaded to the database I want to trigger the second method FirstMonth to start the method.一旦它上传到数据库,我想触发第二个方法FirstMonth来启动该方法。

But the current Issue is before finishing the StartProcess() the second method is starting to process.但是当前的问题是在完成StartProcess()之前,第二种方法开始处理。 How I stop that?我怎么阻止它? I want to trigger second method once the first method is completely finished.一旦第一种方法完全完成,我想触发第二种方法。

You need to await StartProcess() before calling FirstMonth()您需要在调用FirstMonth() await StartProcess() )

This will force execution to wait for StartProcess to finish before it starts FirstMonth :这将强制执行在开始FirstMonth之前等待StartProcess完成:

await StartProcess();

FirstMonth();

Note that the method that executes these needs to be marked async:请注意,执行这些的方法需要标记为异步:

public async Task Foo()
{
    await StartProcess();
    FirstMonth();
}

You should probably await both StartProcess and FirstMonth though.不过,您可能应该同时await StartProcessFirstMonth

If you are tying to wait for the end of the proccess on a sync method on the main thread, then you can simply hit StartProcess().Result or StartProcess.Wait() to run those synchronous.如果您要在主线程上的同步方法上等待进程结束,那么您只需点击StartProcess().ResultStartProcess.Wait()即可运行这些同步。 You can also call yor second method when all the tasks you need are completed, you can check it here当你需要的所有任务都完成后,你也可以调用你的第二种方法,你可以在这里查看

In the case you are calling the tasks you want to be completed inside an async method you can simply use the async await pattern and await StartProcess() .如果您在async方法中调用要完成的任务,您可以简单地使用async await模式和await StartProcess()

I would also suggest you in general to avoid the async void patter.我还建议您总体上避免async void模式。 Link here 链接在这里

you need to change the return type from void to Task in order to wait for the method to complete since the return type is void it will not wait for completion even if you have awaited the call, and then you need to use await keyword for completing the execution.您需要将返回类型从 void 更改为 Task 以等待方法完成,因为返回类型为 void 即使您等待调用也不会等待完成,然后您需要使用 await 关键字来完成执行。 like below.如下所示。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM