Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enforce coding best practices "async void" the right way #6

Open
duongphuhiep opened this issue Aug 12, 2024 · 0 comments
Open

Enforce coding best practices "async void" the right way #6

duongphuhiep opened this issue Aug 12, 2024 · 0 comments

Comments

@duongphuhiep
Copy link

duongphuhiep commented Aug 12, 2024

Hello,

I'm new to Avalonia, so I'm reading the codes here to learn.

However my C# experience tells me that all the async void in this project are not following best practices (hence, got all the problems described in the linked article).

  • Inside every async void function must to be wrapped with try catch, because if something crash in a async void function
    • then (1) the whole application would crashed (while we should pop up an error instead)
    • and (2) outside the async void function You cannot catch the error happening inside and so did not know what happened!
  • The async void function should be minimalist so that the main codes would be testable.

For eg: I would refactor this async void DoSearch(string s) as following

//this "async void" is not testable
private async void DoSearch(string s)
{
    try
    {
        await DoSearchAsync(s);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex); 
        // or send out a "signal" to pop up an error message with all the details of the error
    }
}
//but the important codes here are testable
public async Task DoSearchAsync(string s)
{
    IsBusy = true;
    try
    {
        ...
    }
    finally
    {
        IsBusy = false;
    }
}

Similar, this async void LoadAlbums() should be refactored as following:

//this "async void" is not testable
private async void LoadAlbums()
{
    try 
    {
        await LoadAlbumsAsync();
    }
    catch (Exception ex) 
    {
        Console.WriteLine(ex);
        // or send out a "signal" to pop up an error message with all the details of the error
    }
}

//but the important codes here are testable
public async Task LoadAlbumsAsync()
{
    ...
}

I guess you didn't follow best practices for the sake of simplicity. But as you can see, the codes are not become more complex by following the best pratices. Besides it might inspire other peoples to make more robust applications.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant