繁体   English   中英

如何为其他开发人员提供异步方法?

[英]How can I provide asynchronous methods for other developers?

目前,我的库CherryTomato是我想要的,现在我想为其他开发人员提供异步方法。

目前他们可以使用它:

string apiKey = ConfigurationManager.AppSettings["ApiKey"];

//A Tomato is the main object that will allow you to access RottenTomatoes information.
//Be sure to provide it with your API key in String format.
var tomato = new Tomato(apiKey);

//Finding a movie by it's RottenTomatoes internal ID number.
Movie movie = tomato.FindMovieById(9818);

//The Movie object, contains all sorts of goodies you might want to know about a movie.
Console.WriteLine(movie.Title);
Console.WriteLine(movie.Year);

我可以用什么来提供异步方法? 理想情况下,我想解雇加载,并让开发人员监听一个事件,当它发生时,他们可以使用完全加载的信息。

以下是FindMovieById的代码:

public Movie FindMovieById(int movieId)
{
    var url = String.Format(MOVIE_INDIVIDUAL_INFORMATION, ApiKey, movieId);
    var jsonResponse = GetJsonResponse(url);
    return Parser.ParseMovie(jsonResponse);
}

private static string GetJsonResponse(string url)
{
    using (var client = new WebClient())
    {
        return client.DownloadString(url);
    }
}

处理此问题的标准方法是使用AsyncResult模式。 它在整个.net平台中使用,请查看这篇msdn 文章以获取更多信息。

在.NET 4中,您还可以考虑使用IObservable<>Reactive Extensions一起使用。 对于初学者,从这里抓取WebClientExtensions。 您的实现非常相似:

public IObservable<Movie> FindMovieById(int movieId)
{
    var url = String.Format(MOVIE_INDIVIDUAL_INFORMATION, ApiKey, movieId);
    var jsonResponse = GetJsonResponse(url);
    return jsonResponse.Select(r => Parser.ParseMovie(r));
}

private static IObservable<string> GetJsonResponse(string url)
{
    return Observable.Using(() => new WebClient(),
        client => client.GetDownloadString(url));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM