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

时间:2011-04-21 00:22:39

标签: c# .net asynchronous

目前,我的库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);
    }
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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));
}