How to implement Android callbacks in C# using async/await with Xamarin or Dot42?

后端 未结 2 840
野性不改
野性不改 2021-01-04 09:14

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?

2条回答
  •  抹茶落季
    2021-01-04 09:54

    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.

提交回复
热议问题