简体   繁体   中英

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.

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:

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. It is used throughout the .net platform take a look at this msdn article for some more info.

In .NET 4, you might also consider using IObservable<> to be used with the Reactive Extensions . For starters, grab WebClientExtensions from here . 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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