Xamarin表单 - 异步ContentPage

Ili*_*lov 3 c# asynchronous async-await xamarin.forms

我有以下内容页面,我想在其中加载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
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

我的LineModel类:

public class LineModel
{
        public async Task<Steema.TeeChart.Chart> GetModel ()
        { //some stuff happens here }
}
Run Code Online (Sandbox Code Playgroud)

如何使MainPage异步,这样chartView.Model = await test1.GetModel();可以工作?我试过"异步MainPage"但我收到错误.

Sri*_*vel 9

不,你不能.构造函数不能在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为

MainPage page = await MainPage.CreateMainPageAsync(true);
Run Code Online (Sandbox Code Playgroud)

请注意,我在方法中添加了"Async"后缀,该方法GetModel是用于异步方法的一般约定.