jimmy neutron
jimmy neutron

Reputation: 13

Cannot convert async lambda expression to delegate type 'Func<UIAccessibilityCustomAction, bool>

Getting error:

Error CS4010: Cannot convert async lambda expression to delegate type 'Func'. An async lambda expression may return void, Task or Task, none of which are convertible to 'Func

UIAccessibilityCustomAction someAccessibilityAction = new
                UIAccessibilityCustomAction(
                SwipeActionMarkTextValue("Accessibility Text", false),
                            async (UIAccessibilityCustomAction arg) =>{

                                 await TestAsyncMethod();
                                return true;
                            });


    private async Task<bool> TestAsyncMethod()
    {
         await Task.Delay(5000);
        return true;
    }

Upvotes: 0

Views: 2707

Answers (1)

Marcell Toth
Marcell Toth

Reputation: 3688

Your async method doesn't return a bool. It returns a Task<bool>.

Remember that async is (kindof) syntactic sugar for ContinueWith. Your syntax is perfect but it helps to illustrate my point if I rewrite it as:

(UIAccessibilityCustomAction arg) => TestAsyncMethod().ContinueWith(b => true)

Possible solutions

I am not familiar with Xamarin.iOS, and it also depends on the task you want to achieve but here are some general solutions:

  1. Use an API that accepts an async callback if there is one.
  2. Make your work synchronous.
  3. Wait (block) on your work item:

    /*NO ASYNC HERE*/ (UIAccessibilityCustomAction arg) =>{
        TestAsyncMethod().GetAwaiter().GetResult();
            return true;
        })
    

    Depending on your situation this might cause a deadlock though.

  4. Make your worker "fire and forget" (async void) and immediately return true after kicking it off.

    UIAccessibilityCustomAction someAccessibilityAction = new UIAccessibilityCustomAction(
        SwipeActionMarkTextValue("Accessibility Text", false),
        (UIAccessibilityCustomAction arg) => {
            TestAsyncMethod();
            return true;
        });
    private async void TestAsyncMethod()
    {
        await Task.Delay(5000);
    }
    

Upvotes: 2

Related Questions