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?
while I need it to run on a separate thread- if you are not making that happen yourself inside the method, e.g. withTask.Run(), then that is not going to happen when your method is called withawaiteither, becauseasyncis not about threads.aync/awaitis an implementation detail of the method. The only thing that matters is it returns a Task. If you need to return a task but have no async source just useTask.FromResultTask.Run.Task.Run. As others have said (and as the compiler warnings say if you try to do this),asyncby itself doesn't do anything from the callers perspective.