-2

I have async method called GetDetails(); to get data from API.

public async Task<string> GetDetails(string token, int tenantId, string fromDate,string searchText)
 {
    try
    {
        string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";

        //API callimg code going here....
        
        var response = await client.PostAsync(serviceUrl, content);
        var result = await response.Content.ReadAsStringAsync();
        client.Dispose();
        return result;
    }
}

I need to get above async method data. So I tried do it as follows,

public string GetAllDetails(string token, int tenantId, string fromDate,string searchText)
{
    var dataResult = GetDetails(token,tenantId,fromDate,searchText);
    return dataResult;
}

But I can't call GetDetails async method from non async method. Have any other way to do this? I can make that GetAllDetails() method as async, because it calling from web method as follows.

[WebMethod(EnableSession = true)]
public string GetDetails(string fromDate,string searchText)
{
    try
    {
        SessionState session = new SessionState(Session);
        DetialsConfiguration dc = new DetialsConfiguration();
        string details = dc.GetAllDetails(session.JwtToken, session.ClientId,fromDate,searchText);
        return details;
    }
    catch (Exception ex)
    {
        Logger.LogErrorEvent(ex);
        throw;
    }
}

How can I get GetDetails() API response data to my web method? Please help me to do this?

Liam
  • 27,717
  • 28
  • 128
  • 190
thomsan
  • 433
  • 5
  • 19
  • 1
    Does this answer your question? [How to call asynchronous method from synchronous method in C#?](https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c) – Liam Jan 13 '21 at 09:11

1 Answers1

0

How get async method value from non async method

You don't... unless you have a very specific use case. Instead you let the async and await pattern propagate

public async Task<string> GetAllDetails(string token, int tenantId, string fromDate,string searchText)
{
    var dataResult = await GetDetails(token,tenantId,fromDate,searchText);
    return dataResult;
}

...

[WebMethod(EnableSession = true)]
public async Task<string> GetDetails(string fromDate,string searchText)
{
    try
    {
        SessionState session = new SessionState(Session);
        DetialsConfiguration dc = new DetialsConfiguration();
        string details = await dc.GetAllDetails(session.JwtToken, session.ClientId,fromDate,searchText);
        return details;
    }
    catch (Exception ex)
    {
        Logger.LogErrorEvent(ex);
        throw;
    }
}

Also note any async methods should have the Async Suffix E.g GetAllDetailsAsync

TheGeneral
  • 79,002
  • 9
  • 103
  • 141