简体   繁体   English

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

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

For now, my library CherryTomato is where I want it to be, and now I'd like to provide asynchronous methods for other devs to use. 目前,我的库CherryTomato是我想要的,现在我想为其他开发人员提供异步方法。

Currently here's how they can use it: 目前他们可以使用它:

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);

What can I use to provide asynchronous methods? 我可以用什么来提供异步方法? Ideally I'd like to fire the loading, and let the devs listen for an event to fire and when it fires they can then use the fully loaded information. 理想情况下,我想解雇加载,并让开发人员监听一个事件,当它发生时,他们可以使用完全加载的信息。

Here is the code for FindMovieById: 以下是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);
    }
}

the standard way to handle this is using the AsyncResult pattern. 处理此问题的标准方法是使用AsyncResult模式。 It is used throughout the .net platform take a look at this msdn article for some more info. 它在整个.net平台中使用,请查看这篇msdn 文章以获取更多信息。

In .NET 4, you might also consider using IObservable<> to be used with the Reactive Extensions . 在.NET 4中,您还可以考虑使用IObservable<>Reactive Extensions一起使用。 For starters, grab WebClientExtensions from here . 对于初学者,从这里抓取WebClientExtensions。 Your implementation is then pretty similar: 您的实现非常相似:

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