问题
I need to call a async
method from my Form1
constructor. Since a constructor can't have a return type, I can't add a async void
. I read that static constructor can be async
but I need to call methods from constructor that aren't static
, such as InitializeComponent()
(since it's the Form's constructor).
The class is:
public partial class Form1 : Form
{
InitializeComponent();
//some stuff
await myMethod();
}
I read this one too but I still don't know how to implement this (in my case) since the method still requires to use async
.
回答1:
Don't do this in the constructor but in the loaded event of the window instead. You can mark the loaded eventhandler as async.
回答2:
You can use a static method that returns an instance of your form
public class TestForm : Form
{
private TestForm()
{
}
public static async Task<TestForm> Create()
{
await myMethod();
return new TestForm();
}
}
回答3:
My sample is to call student details from page constructor
1- the calling of navigation page
void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
Student _student = (Student)e.Item;
Navigation.PushAsync(new Student_Details(_student.ID));
}
2 - the details page
public partial class Student_Details : ContentPage
{
public Student_Details(int id)
{
InitializeComponent();
Task.Run(async () => await getStudent(id));
}
public async Task<int> getStudent(int id)
{
Student _student;
SQLiteDatabase db = new SQLiteDatabase();
_student = await db.getStudent(id);
return 0;
}
}
回答4:
While common advice dictates you generally shouldn't do it in the constructor, you can do the following, which I have used in apps, such as console apps, where I need to call some existing async code:
DetailsModel details = null; // holds the eventual result
var apiTask = new Task(() => details = MyService.GetDetailsAsync(id).Result); // creates the task with the call on another thread
apiTask.Start(); // starts the task - important, or you'll spin forever
Task.WaitAll(apiTask); // waits for it to complete
Philip is correct that, if you can avoid doing this in a constructor, you should.
回答5:
Task.Run(async () => await YourAsyncMethod());
来源:https://stackoverflow.com/questions/29054202/how-can-i-call-async-method-from-constructor