我有以下内容页面,我想在其中加载Steema Teechart,但我不能,因为我无法使MainPage异步:
我的主页:
public class MainPage : ContentPage
{
public MainPage (bool chart)
{
ChartView chartView = new ChartView
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 300,
WidthRequest = 400
};
LineModel test1 = new LineModel();
chartView.Model = await test1.GetModel();
//put the chartView in a grid and other stuff
Content = new StackLayout {
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Children = {
grid
}
};
}
}
我的LineModel类:
public class LineModel
{
public async Task<Steema.TeeChart.Chart> GetModel ()
{ //some stuff happens here }
}
如何使MainPage异步以便chartView.Model = await test1.GetModel();
可以正常工作?我尝试过“异步MainPage”但我收到了错误。
答案 0 :(得分:8)
不,你不能。 Constructor can't be async in C#;典型的解决方法是使用异步工厂方法。
public class MainPage : ContentPage
{
public MainPage (bool chart)
{
ChartView chartView = new ChartView
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 300,
WidthRequest = 400
};
}
public static async Task<MainPage> CreateMainPageAsync(bool chart)
{
MainPage page = new MainPage();
LineModel test1 = new LineModel();
chartView.Model = await test1.GetModelAsync();
page.Content = whatever;
return page;
}
}
然后将其用作
MainPage page = await MainPage.CreateMainPageAsync(true);
请注意,我为方法GetModel
添加了“Async”后缀,这是用于异步方法的一般约定。