Search code examples
c#wpfasync-await

Async await Task error for load files in WPF


I am trying to do an async operation in UploadBtnExecute method.I am working this on wpf. But it shows some error.

error are :- error 1::-'

Task UploadBtnExecute(object)' has the wrong return type

error 2::- '

bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)

What I have tried:

button click event to trigger a function

UploadBtnClick = new RelayCommands(UploadBtnExecute,UploadBtnCanExecuteUpload);

public async Task UploadBtnExecute(object param)
{
    Progress windowShow = new Progress();
    windowShow.Show();
    await UploadFiles();
    windowShow.Hide();
}

public bool UploadFiles(List<Item> selectedFiles)
{
    //do some upload code here
    return true;
}

Solution

  • Error 1:

    An event handler must return void. This is this case where using async void instead of using async Task is recommended (mainly because there is no alternative, actually) for an async function that doesn't return a value.

    Error 2:

    Your second UploadFiles must return a Task<bool> instead of bool for await to make any sense.

    Additionally, since this is the function actually doing something asynchronous, you probably wait it to be async Task<bool> and use await on the actual code that uploads something, but that may depend on your actual goal.

    So as a summary, your snippet of code should be adapted like that:

    UploadBtnClick = new RelayCommands(UploadBtnExecute,UploadBtnCanExecuteUpload);
    
    public async void UploadBtnExecute(object param)
    {
        Progress windowShow = new Progress();
        windowShow.Show();
        await UploadFiles();
        windowShow.Hide();
    }
    
    public async Task<bool> UploadFiles(List<Item> selectedFiles)
    {
        // do some upload code here
        // using await ....
        return true;
    }
    
    // alternatively:
    public Task<bool> UploadFiles(List<Item> selectedFiles)
    {
        // do some upload code here
        return Task.FromResult(true);
    }