async Task await and Threads - background work

Hi All,

I'm currently writing a Xamarin android app and wanted to know how people are handling background work for things such as reading from a database and other I/O that could potentially take a few seconds to complete and hang the UI thread.

I'd really like to take advantage of the Task based approach, using async await but this is hard to do in android because most methods are overrides such as activitycreate

protected override void OnCreate(Bundle savedInstanceState)
{
    ...
}

and a fragment method

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    ...
}

As you are probably aware the base android methods do not have "Async" versions meaning you are unable to await anything inside of them, the methods do not block when an await is reached.

I came across this article this morning and wondered if this is the only approach and if this is the way everyone else is doing it?

Thanks
Phil

Posts

  • RofiqSetiawanRofiqSetiawan USMember ✭✭✭

    @Phil.2708
    how about this one

    async protected override void OnCreate (Bundle savedInstanceState)
    {
       // your code
    }
    

    but I prefer to use Task coz i don't need to change default code

    Task.Run(
        async () => await MySomethingAsync()
    );
    
Sign In or Register to comment.