How do you implement callbacks in C# using async/await with Xamarin for Android? And how does this compare to standard Java programming for Android?
I use the following model to convert call backs to async:
SemaphoreSlim ss = new SemaphoreSlim(0);
int result = -1;
public async Task Method() {
MethodWhichResultsInCallBack()
await ss.WaitAsync(10000); // Timeout prevents deadlock on failed cb
lock(ss) {
// do something with result
}
}
public void CallBack(int _result) {
lock(ss) {
result = _result;
ss.Release();
}
}
This is very flexible and can be used in Activities, inside callback objects ect.
Be careful, using this the wrong way will create deadlocks ect. The lock prevents result changing after if the timeout runs out.