0

I would like to know what is the difference between

public Task<string> MyString()
{
    ....
}

And

public string MyString()
{
    ....
}

Is it safer to use Task on the server-side when multiple users run it in the same time? By "safer" I mean situation when I have a login logic in that function which returns an ID to a client (WPF) side. This logic is basically adding to cache dictionaries (ConcurrentDictionary). So is it possible that using the second option my server will be blocked when multiple users will run it at the same time? Thanks.

Michal_Drwal
  • 526
  • 1
  • 9
  • 26
  • 4
    You probably should read https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await and than [edit] the question to clarify what you trying to understand here... Additionally "safer"/"better"/"cleaner" are way too generic terms and do make question poorly defined - you may want to replace that with some sort of explanation of what you mean as "safer"... – Alexei Levenkov Feb 11 '21 at 02:12

1 Answers1

0

If you declare your method as Task<string> but remove the async, you will not be able to await within it and just because you add async to a method which doesn't use any other async methods (with await) you will not get asynchronous execution (the compiler even warns you about this). You can force it to be run async but it has no performance boost it will just create an overhead (see this answer). So all in all, if you have an async method inside your MyString method, then you should use async Task<string> if you don't then just use string there is no need to force asynchronous execution on it.

BenceL
  • 804
  • 6
  • 13