Vke Vke - 21 days ago 4
C# Question

how to wait for await in async method to finish the all the executions?

For the following code im calling that async void method.

public void LoadSystemDetails(int clientId)
{
DataSystem.Name = "Salesforce System";
DataSystem.Description = "";
GetAllFields(clientId);
}


following code is
GetAllFields
method

public async void GetAllFields(int clientId)
{
this.DataSystem.SystemTables = new List<DataSystemTable>();


using (var forceClient = await ConnectToSalesforceByOAuth(clientId))
{
var SalesForceTable = new DataSystemTable
{
TableName = "Contact"
};
DataSystem.SystemTables.Add(SalesForceTable);

var contact = forceClient.DescribeAsync<SalesforceObject>("Contact");
var tableFields = new List<DataSystemField>();

foreach (var con in contact.Result.Fields)
{
tableFields.Add(new DataSystemField
{

ColumnName = con.Name,

});
}

SalesForceTable.EissSyncSystemFields = tableFields;
}


and i call
callbackScript
as below.

callbackScript.AppendLine(string.Format("var destinationSystem ={0};", JsonConvert.SerializeObject(this.DestinationSystem, Formatting.Indented)));


here
DestinationSystem
is calling the
LoadSystemDetails
. Like
DestinationSystem.LoadSystemDetails(clientId)


while
using (var forceClient = await ConnectToSalesforceByOAuth(clientId))
line is execute at the time the
callbackScript
is executed. so the
SystemTables
doesn't have any value. but it having
Name
and
Description
.

so here i need to wait the
LoadSystemDetails
to finish the
GetAllFields
.

How i do that.Please help me.
Thanks.

Answer

If you need LoadSystemDetails to wait for GetAllFields, there are 2 problems here:

  • you are calling async method from a synchronous context
  • GetAllFields is async void, which means fire and forget. You will never be able to wait for it to finish.

Solution: First, NEVER use async void if you need to wait for the result or end. Use async Task instead
Second, either convert LoadSystemDetails to async method also, then await the GetAllFields (that should return Task), or use GetAllFields(clientId).Wait()

take a look at this article for more information on async/await: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Comments