1

I have a conditional synchronous method (hereinafter "GenString"). I decided to make it asynchronous. I got 2 variations. But I would like to know how to do it right? I'll be grateful for examples.

async Task<string> GenStringAsynV2(long arrayLength)
{
    return await Task.Run(() => GenString(arrayLength));
}

Task<string> GenStringAsynV1(long arrayLength)
{
    return Task.Run(() => GenString(arrayLength));
}
string GenString(long arrayLength)
{
    Stopwatch sw = Stopwatch.StartNew();

    StringBuilder result = new();
    for (long i = 0; i < arrayLength; i++)
    {
        result.Append(i).Append(" + ");
    }

    sw.Stop();
    StringBuilder timeWork = new StringBuilder("GenString: ")
        .Append(sw.Elapsed)
        .Append("; String Length: ")
        .Append(result.Length);
    Debug.WriteLine("End");
    return timeWork.ToString();
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 2
    Your `GetString` method doesn't do anything asynchronously. There are many, many articles online about how to make a function asynchronous in C#; [Microsoft's own documentation on the subject is actually not that bad](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/), – Heretic Monkey Aug 07 '22 at 21:12
  • I don't understand why you would want to make the presented code asynchronous, it's just string manipulation. – gunr2171 Aug 07 '22 at 21:14
  • 2
    Important reading: ​​[Should I expose asynchronous wrappers for synchronous methods?](https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/) by Stephen Toub. Also this: [Eliding Async and Await](https://blog.stephencleary.com/2016/12/eliding-async-await.html) by Stephen Cleary. – Theodor Zoulias Aug 07 '22 at 21:20
  • @HereticMonkey, Me interests as without touching a normal method to make it asynchronously. How is it done correctly and is it possible. – Sir Percyvelle Aug 07 '22 at 21:25
  • @gunr2171, It makes no sense, I created this example to better understand asynchrony. It doesn't carry any meaning. – Sir Percyvelle Aug 07 '22 at 21:27
  • @TheodorZoulias, Thanks for the articles, I will definitely read them, although first I will try to find them in my native language – Sir Percyvelle Aug 07 '22 at 21:42

0 Answers0