简体   繁体   中英

c# Writing an async method that doesn't have an await in it

I want to have an async method in my call that would be called by my library consumers with an await . But the internal working of my method, while I need it to run on a separate thread, does not call any other await on it's own.

I just do the work the method is supposed to do and return the type. And the compiler warns me that this method will not run in an async way.

public async Task<MyResultObject> DoSomeWork()
{
     MyResultObject result = new MyResultObject();
     // Some work to be done here

     return result;
}

On the other hand, if I write a method that starts a new task using TaskFactory like this:

public Task<MyResultObject> DoSomeWork()
{
     return Task<MyResultObject>.Factory.StartNew(() =>
     {
         MyResultObject result = new MyResultObject();
         // Some work to be done here

         return result;
     });
}

Then I cannot call it using the await keyword like this await DoSomeWork() .

How do I write an async (must be async and not task with result or wait) without using some await call inside?

You can do this

public Task<MyResultObject> DoSomeWork()
{
     MyResultObject result = new MyResultObject();
     // Some work to be done here

     return Task.FromResult(result);
}

which is exactly the same as

public async Task<MyResultObject> DoSomeWork()
{
     MyResultObject result = new MyResultObject();
     // Some work to be done here

     return result;
}

Only this version gives a warning and has slightly more overhead.

But neither will run on another thread. The only benefit is that they have an awaitable interface.

To do it in parallel, your code is Ok but Task.Run is preferred over StartNew():

public Task<MyResultObject> DoSomeWork()
{
     return Task.Run(() =>
     {
         MyResultObject result = new MyResultObject();
         // Some work to be done here

         return result;
     });
}

And in all these cases you can definitely await DoSomeWork()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM