【问题标题】:How to make a request asynchronously in c# (xamarin)?如何在 c# (xamarin) 中异步发出请求?
【发布时间】:2016-05-25 13:07:39
【问题描述】:

我曾经使用基于浏览器的应用程序。例如 Angular 简单存储库。

function getSomeData(params) {
        ...
        return $http({
            url: conf.urlDev + 'some/rest-url',
            method: "GET",
            params: params,
            cache: true
        }).then(getDataComplete);

        function getDataComplete(response) {

            return response.data;
        }
    }

它在 c# 中的外观如何(例如 XAMARIN)? 我试试:

 public class BaseClient 
{
    protected Http _client = null;
    protected string _urlObj;
    protected string _basePath;

    public BaseClient ()
    {
        _client = new Http(new HttpClientHandler());
    }

    public string Path
    {
        set
        {
            _urlObj = value;
        }
    }

    public async Task<Result<IList<T>>>getList<T>(Dictionary<string,object> parametrs = null)
    {
        if (parametrs != null)
        {
            foreach(KeyValuePair<string, object> keyValue in parametrs)
            {
                _urlObj = _urlObj.SetQueryParam(keyValue.Key, keyValue.Value);
            }
        }

        var response = await _client.GetAsync(_urlObj.ToString());

        if (response.IsSuccessStatusCode)
        {
            return new Result<IList<T>>()
            {
                Success = true,
                Value = JsonConvert.DeserializeObject<IList<T>>(await response.Content.ReadAsStringAsync())
            };
        }
        else
        {
            var error = new Result<IList<T>>()
            {
                Error = response.StatusCode.ToString(),
                Message = response.ReasonPhrase,
                Success = false
            };

            return error;
        }
    }

为我服务:

public async Task<IList<News>> GetAllNewsByParams(DateTime from,
                            string orderBy = "-published",
                            DateTime to = new DateTime(),
                            int page = 1, int category = 0)
    {
        _client.Path = _config.NewsPath;

        var  dict = new Dictionary<string, object> {
            {"from", from.ToString("s")},
            {"order_by", orderBy.ToString()},
            {"to", to.ToString("s")},
            {"page", page.ToString()}
        };

        if (category != 0)
        {
            dict.Add("category", category.ToString());
        }

        var res = await _client.getList<News>(dict);

        return res.Value;
    }

还有我的视图模型

foreach (var item in await _newsService.GetAllNewsByParams(
                                         _To,
                                         _OrderBy,
                                         _From, _Page,
            selectedTag == null ? _SeletedNewsTagId : selectedTag.Id))
        {
            NewsList.Add(item);
        }

他的查询是同步执行的吗? 我如何使它成为异步的?

【问题讨论】:

  • 如果异步是指在等待响应时不占用线程,那么是的,您的操作是纯异步的。
  • 即不应该有.then({})?
  • async/await 是基于回调的异步操作的抽象:您可能会将then 回调视为await 行下的所有内容。

标签: c# angularjs asynchronous xamarin


【解决方案1】:

首先,我真的鼓励您使用 RestSharp,它确实简化了 HTTP 请求的发出和反序列化。将RestSharp nuget package 添加到您的项目中。这是您的代码使用 RestSharp 时的样子。

public class BaseClient
{
    protected IRestClient _client = null;
    protected string _urlObj;
    protected string _basePath;

    public BaseClient()
    {
        _client = new RestClient();
    }

    public async Task<Result<IList<T>>> GetList<T>(string path, Dictionary<string, object> parametrs = null)
    {
        var request = new RestRequest(path, Method.GET);
        if (parametrs != null)
        {
            foreach (var keyValue in parametrs)
            {
                request.AddQueryParameter(keyValue.Key, keyValue.Value);
            }
        }

        var response = await _client.Execute<List<T>>(request);

        if (response.IsSuccess)
        {
            return new Result<IList<T>>()
            {
                Success = true,
                Value = response.Data
            };
        }
        else
        {
            var error = new Result<IList<T>>()
            {
                Error = response.StatusCode.ToString(),
                Message = response.StatusDescription,
                Success = false
            };

            return error;
        }
    }
}

为您服务

public async Task<IList<News>> GetAllNewsByParams(DateTime from,
                        string orderBy = "-published",
                        DateTime to = new DateTime(),
                        int page = 1, int category = 0)
    {

        var dict = new Dictionary<string, object> {
                        {"from", from.ToString("s")},
                        {"order_by", orderBy.ToString()},
                        {"to", to.ToString("s")},
                        {"page", page.ToString()}
                    };

        if (category != 0)
        {
            dict.Add("category", category.ToString());
        }

        var res = await _client.GetList<News>(_config.NewsPath, dict);

        return res.Value;
    }

在你的视图模型中

var news = await _newsService.GetAllNewsByParams(
                                     _To,
                                     _OrderBy,
                                     _From, _Page,
            selectedTag == null ? _SeletedNewsTagId : selectedTag.Id);
foreach (var item in news)
{
    NewsList.Add(item);
}

这将是 100% 异步的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多