Assume that a virtual function virtual OnUpdate() is defined in the base class and the user overrides it in the derived class to implement the process.
I would like to co-routine this OnUpdate() like Unity so that it runs asynchronously and simultaneously, but should I define the virtual method with the async keyword when implementing using wait/async?
class Base {
public async virtual Task OnUpdate() {
}
}
class Derived: Base {
public async override Task OnUpdate() {
}
}
First, it is OK for the language to attach the async keyword to the virtual method.There is no problem override in the derived class.This works fine.Additionally, the async keyword is not included in the method signature.
However, if implemented as above, there are two problems.
1st: The compiler warns you of async for methods that do not have await
Second: Return value Task (or Task<T>
) that must be written in an unusual way is not smart
Furthermore, users are not very interested in asynchronous processing and do not want to see async or Task.
So you can rewrite it using the Non-Virtual Interface idiom to write it elegantly.
class Base {
public async Task Update() {
waitTask.Run(()=>{
OnUpdate();
});
}
protected virtual void OnUpdate() {
}
}
class Derived: Base {
protected override void OnUpdate() {
}
}
Virtual OnUpdate() now runs asynchronously in the same way as before.
© 2024 OneMinuteCode. All rights reserved.