1

I keep on staring at this code but cannot figure out how to fix it correctly. I have a UITextField. If RETURN is pressed, it is supposed to execute an async method. The code below gives me a compiler warning that I should consider using await HandleNextStep(). Can't do that because ShouldReturn is not async:

delegate bool UITextFieldCondition(UITextField textField);

Can I fix this? Should I fix it? Does it matter if ShouldReturn() returns immediately before HandleNextStep() is finished?

this.txt.ShouldReturn = textField =>
{
    this.HandleNextStep();
    return true;
};
Krumelur
  • 32,180
  • 27
  • 124
  • 263
  • Not a monotouch developer but if you don't want the keyboard to dismiss until the async operation is complete return NO there, disable keyboard, display progress and then enable the textField and call `endEditing` on the parent view once the async operation completes successfully. – Joe Jan 08 '14 at 20:53

2 Answers2

2

Not a Monotouch developer either, but I'd assume you can ignore this warning, unless you're really interested in observing the completion of the task returned by the HandleNextStep() asynchronous call.

The following would suppress the warning in VS 2012:

this.txt.ShouldReturn = textField =>
{
    var task = this.HandleNextStep(); // presumably, no more warning
    return true;
};

If you actually like to observe the status of the task, you could do something like this (no more warning):

Task _handleNextStepTask; // a member variable

// ... 

this.txt.ShouldReturn = textField =>
{
    this._handleNextStepTask = this.HandleNextStep().ContinueWith(
        t => Debug.Print("NextStepHandled"), 
        TaskScheduler.FromCurrentSynchronizationContext());
    return true;
};

Or even something like below, if you really don't want to store the Task object anywhere, still no more warning:

this.txt.ShouldReturn = textField =>
{
    (new Action(async () =>
    {
        try
        {
            await this.HandleNextStep();
            // executed synchronously until this point
            Debug.Print("NextStepHandled");
        }
        catch (Exception ex)
        {
            // catch all exceptions inside "async void" lambda
            Debug.Print(ex.Message);
        }
    }))();

    return true;
};

The latter approach might be perceived as code smell, but I think in this specific case it can be used.

Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486
-1

I believe you can use an async lambda for your event.

this.txt.ShouldReturn = async textField =>
{
    await this.HandleNextStep();
    return true;
};

edit: There is a good example of this here: http://msdn.microsoft.com/en-us/library/bb397687.aspx under "Async Lambda's"

Adam Modlin
  • 2,994
  • 2
  • 22
  • 39