Is it possible to use await in an event?

Kim Strasser 811 Reputation points
2024-06-27T13:16:09.2433333+00:00

I tried to use await in this event:

CrossMediaManager.Current.MediaItemFinished += (s, e) => 
{      
    customDialog.Cancel(); 
    await ResumeSong(7, TimespanIngamemenuPosition);      
};

public async Task<bool> ResumeSong(int resumesong, TimeSpan songtimespan)
{
     bool resume = false;
     ...


     return resume;
}

Error CS4034 The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

I have tried to change it to:

async CrossMediaManager.Current.MediaItemFinished += (s, e) => 
{          
    customDialog.Cancel();     
    await ResumeSong(7, TimespanIngamemenuPosition);      
};

But then I get many errors:

Error CS0841 Cannot use local variable 'CrossMediaManager' before it is declared Error CS0246 The type or namespace name 'async' could not be found (are you missing a using directive or an assembly reference?) Error CS1003 Syntax error, ',' expected Error CS1002 ; expected Error CS0103 The name 'Current' does not exist in the current context

Is it possible to use await in this event or should I execute ResumeSong without the await in CrossMediaManager.Current.MediaItemFinished?

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,814 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,134 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 60,201 Reputation points
    2024-06-27T15:43:59.7033333+00:00

    the correct syntax is:

    CrossMediaManager.Current.MediaItemFinished += async (s, e) => 
    {      
        customDialog.Cancel(); 
        await ResumeSong(7, TimespanIngamemenuPosition);      
    };
    
    

    but the event callback will not await as it does not support async callbacks. it basically a fire and forget call. so the following will also work the same:

    CrossMediaManager.Current.MediaItemFinished += (s, e) => 
    {      
        customDialog.Cancel(); 
        ResumeSong(7, TimespanIngamemenuPosition);      
    };
    
    

    the await is only useful if there is some code after the ResumeSong() call.

    0 comments No comments

0 additional answers

Sort by: Most helpful