【问题标题】:Return values from asynchronous function Xamarin从异步函数 Xamarin 返回值
【发布时间】:2017-11-22 13:30:34
【问题描述】:

我使用 Xamarin 开发移动应用程序

打印从网络服务获得的数据需要做什么

Json 格式化

异步函数

public async Task<List<MesajModel>> MesajAl()
{
    MesajModel obj =new MesajModel();
    List<MesajModel> mesaj =new List<MesajModel>();

    string url = "https://jsonplaceholder.typicode.com/posts/1";

    try
    {
        HttpClient cl = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

        HttpResponseMessage response = await cl.SendAsync(request);

        HttpContent content = response.Content;

        var statusCode = response.StatusCode;

        string json = await content.ReadAsStringAsync();
        obj.Aciklama = json.ToString();
        obj.Mesaj = "Yaptik";
        mesaj.Add(obj);
        return mesaj;
    }
    catch (Exception e)
    {
        return mesaj;
    }
}

我要触发的函数 按钮单击的 Xamarin.Form 事件

private void Button_Clicked(object sender, EventArgs e)
{
    var a=con.MesajAl().Wait();
}

【问题讨论】:

    标签: c# json asynchronous xamarin


    【解决方案1】:

    按钮点击事件应该写成:

    private async void Button_Clicked(object sender, EventArgs e)
    {
       var a = await con.MesajAl();
    }
    

    使用await 等待响应并生成事件async

    【讨论】:

      【解决方案2】:

      您只需使用 await 调用该方法。

      这是来自 msdn 的 async/await 操作的一个很好的参考。

      async

      await

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-14
        • 2020-09-12
        • 2020-07-29
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        • 2018-04-09
        相关资源
        最近更新 更多