2011-04-21 40 views
3

现在,我的库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); 
    } 
} 
+0

事件/代表 – Jacob 2011-04-21 00:27:06

+3

这完全是主观判断,但我会花那个时间做其他的事情,比如测试我的图书馆,以确保其安全地从多个线程调用。用户可以随时添加他们自己的异步包装器。也就是说,除非您可以提供跟踪进度的方式,否则用户会从使用库的异步实现中看到真正的好处。请参阅此相关问题的答案:http://stackoverflow.com/questions/1663871/should-i-provide-sync-or-async-methods-for-developers-in-my-imdb-api-library – 2011-04-21 00:32:58

+0

@Merlyn:你的建议允许开发人员以异步方式封装进程是有意义的。嗯...我没想到会出现这种灰色阴影。 – 2011-04-21 00:38:02

回答

2

来处理,这是使用AsyncResult模式的标准方法。它用于整个.net平台,请查看此msdn article获取更多信息。

+0

谢谢,我会给这个读。 :) – 2011-04-21 00:30:13

2

在.NET 4中,您也可以考虑使用IObservable<>Reactive Extensions一起使用。对于初学者,请从here获取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)); 
} 
+0

我想Rx也适用于.NET 3.5,Silverlight 3+和Windows Phone 7,所以这不仅适用于.NET 4。 – dahlbyk 2011-04-21 00:40:50

相关问题