0
votes

I'm working on Xamarin Forms project in Visual Studio 2017 . I need to implement async method inside thread .

Event which starting the thread

   public void btnAction_Click(object sender, System.EventArgs e)
    {
        var load = new System.Threading.Thread((t) =>
        {
           ShowWarning();

        });
        load.Start(btnText);

    }

async method should implement inside the thread

 private async void ShowWarning()
 {
       bool response = await  DisplayAlert("Warning", "Please Enter
                            The Key","Yes","No");
 }
1
async void is only meant for event handlers. Why use a thread at all? - Panagiotis Kanavos
Why do you need to do that? What does it mean to "implement a task in a thread"? - Lasse V. Karlsen
Inside that method there is another part of function as well (not mentioned it in here ) that's why i put it inside a thread - charitht99 perera

1 Answers

3
votes

If DisplayAlert is truely asynchronous, why do you start a thread at all? You can declare your event handler async and simply awiat ShowWarning:

public async void btnAction_Click(object sender, System.EventArgs e)
{
    await ShowWarning();
}

You might want to disable btnAction before the await and re-enable it after the await again, so you avoid another click event while awaiting.


And note that it's bad practice to declare ShowWarning as async void. It should be

private async Task ShowWarning()
{ ... }

(In case of the button event handler it's ok to return async void because otherwise you couldn't assign it to an event).


If you really need to run ShowWarning on a different thread, you can use Task.Run():

public async void btnAction_Click(object sender, System.EventArgs e)
{
    await Task.Run(ShowWarning);
}