C# - Making sync function to async

sravan kumar 121 Reputation points
2021-02-17T19:11:01.157+00:00

Hi,

I am just wondering if below code changes (New Code) make any difference in performance with respective to calling cosmos from a web api

Old Code:

public string GetDocs()
{
return JsonConvert.SerializeObject(CreateDocumentQuery().ToList());
}

New Code:

public Task<string> GetDocs()
{
return JsonConvert.SerializeObject(CreateDocumentQuery().ToList());
}

So adding Task<string> makes the method async or will it make any difference?

please help in understanding this, Thanks in advance.

Regards,
Sravan kumar

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,997 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
341 questions
{count} vote

6 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,061 Reputation points
    2021-09-03T15:46:05.227+00:00

    Old Code:

    public string GetDocs()
    {
    return JsonConvert.SerializeObject(CreateDocumentQuery().ToList());
    }

    New Code (properly written - while async would work, it gives compile warnings):

    public Task<string> GetDocs()
    {
    return Task.ResultFrom(JsonConvert.SerializeObject(CreateDocumentQuery().ToList());
    }

    this code converts sync code to callable as async (returns a Task), but does not make the code actually async. You are just adding the async calling overhead.

    you need to use cosmos db async access methods if you want to improve performance. if this is for asp.net core, you should always use the async versions and never use the sync methods (ToList(), First(), etc).

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.