-3

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

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. Once it uploaded to the database I want to trigger the second method FirstMonth to start the method.

But the current Issue is before finishing the StartProcess() the second method is starting to process. How I stop that ? I want to trigger second method once the first method is completely finished.

Yrox Mk
  • 49
  • 10
  • 3
    So, you know that compiler warning that says "because this call is not awaited, execution continues.."; you're now here with the complaint "execution is continuing!" - always pay close attention to warnings too; just because your app works even if there are hundreds of them doesn't mean it's error free – Caius Jard Dec 20 '21 at 09:12
  • 1
    `throw ex;` -> please don't. Just remove the try-catch if you're not going to do anything with the exception. `throw ex;` is almost never something you want – Camilo Terevinto Dec 20 '21 at 09:13
  • 1
    Indeed; the only time you should realistically have an async void is probably in a windows forms event handler – Caius Jard Dec 20 '21 at 09:15
  • 1
    any time you type the words `async void`, you're *probably* making a mistake; there *are* some scenarios where it is necessary (UI event-handlers being the classic example), but the rest of the time...? – Marc Gravell Dec 20 '21 at 09:19
  • Don't access windows forms controls in this way; you're risking accessing them from threads other than the threads that created them – Caius Jard Dec 20 '21 at 09:38
  • Show us the contents of `DbLoad.UploadStock();` – Caius Jard Dec 20 '21 at 10:12
  • @CaiusJard I have update the question and pasted the code. – Yrox Mk Dec 20 '21 at 11:04
  • Erm.. I can see some bits, but UploadStock is missing. UpdateFirstMonth has appeared too, and doesn't have any definition.. – Caius Jard Dec 20 '21 at 18:10

3 Answers3

0

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. 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().

I would also suggest you in general to avoid the async void patter. Link here

Mr.Deer
  • 476
  • 6
  • 17
0

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. 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;
    }
 }
Vilsad P P
  • 1,529
  • 14
  • 23
-1

You need to await StartProcess() before calling FirstMonth()

This will force execution to wait for StartProcess to finish before it starts FirstMonth:

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.

Ortund
  • 8,095
  • 18
  • 71
  • 139