简体   繁体   中英

Interface Requiring Function That Returns Task

I have an interface that requires a certain function which returns Task. In one of the classes that implement this interface, I don't need to do anything whatsoever in this function. However, this understandably presents me with a helpful warning: Function 'MoveToNextField' doesn't resturn a value on all code paths. A null reference exception could occur at run time when the result is used.

Public Function MoveToNextField() As Task Implements FormObjects.Interfaces.IViewer.MoveToNextField

End Function

This presents an issue as the code calling it (below) is going to await this function. If I fail to return anything, I'll get a null reference exception.

await objExample.MoveToNextField()

However, since I have nothing to await, changing the function to the below also presents me with a warning: This async function lacks 'Await' operators and so will run synchrounsly. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.

Public Async Function MoveToNextField() As Task Implements FormObjects.Interfaces.IViewer.MoveToNextField

End Function

So, my question is: What is the most correct way of solving this? The below code works and produces no errors, but I'm not convinced it is the best way:

Public Function MoveToNextField() As Task Implements FormObjects.Interfaces.IViewer.MoveToNextField
    Return Task.Run(Sub()
                    End Sub)
End Function

You could Return Task.CompletedTask . This is useful in cases like the one you describe where you need to satisfy an interface method that returns a Task, but you have nothing to await in your concrete implementation.

Public Function MoveToNextField() As Task Implements FormObjects.Interfaces.IViewer.MoveToNextField
    Return Task.CompletedTask
End Function

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