[英]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.