Any disadvantage to creating a class which uses methods which return a Task<T> but are synchronous methods over methods returning T

柔情痞子 提交于 2021-01-29 04:43:18

问题


Let's say we have this class - MyClass

MyClass has methods that convert different types of lists to XDocuments

As an example we'll just look at one method, Convert

I could write this method as:

public XDocument Convert<T>(IList<T> myList)
{
    XDocument doc = new XDocument("root");
    //Do some synchronous work       
    return doc;
}

Or I could write it like the following:

public Task<XDocument> Convert<T>(IList<T> myList)
{
    XDocument doc = new XDocument("root");
    //Do some synchronous work       
    return Task.FromResult(doc);
}

Now imagine we want to offload this to a Task in another part of our program, while some other tasks are doing some work and then await them all to complete before doing some other work inside the async method.

I know with the first version of the method, I could do:

some async method...

Task t = Task.Run(() => myClass.Convert<T>(IList<T>);
Task t2...
Task t3...
await Task.WhenAll(t, t2, t3);

But with the second form of the method, it seems more simplistic to be able to do:

some async method...

Task t = myClass.Convert<T>(IList<T>);
Task t2...
Task t3...
await Task.WhenAll(t, t2, t3);

My question is:

Is there any downside to designing the method like the second example? To return a Task for ease of use in running as Task elsewhere in the code base, even though it is synchronous. Or is this more about intent?

I know this may be considered an opinionated question, so I will probably remove it from SO after I have given it enough time to gain some responses. Otherwise, if considered a specific enough and good question, I will leave it.


回答1:


Is there any downside to designing the method like the second example?

Yes. The method is synchronous, but it has an asynchronous signature. This is a poor design choice.

This can easily cause accidental misuse. Say, for example...

it seems more simplistic to be able to do

That code won't work the way you think it will. The tasks will not run in parallel. Because the code is synchronous; it just has an asynchronous signature.

And if you think of using Task.Run as the implementation of a fake-asynchronous method, that's also considered a bad practice.




回答2:


Your two examples do not do the same thing. In the first example, where you use Task.Run, you are spinning work off to the thread pool to execute in parallel. Asynchronous tasks do not use the thread pool; they use cooperative multitasking to complete asynchronous operations in parallel.



来源:https://stackoverflow.com/questions/65617912/any-disadvantage-to-creating-a-class-which-uses-methods-which-return-a-taskt-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!