1

我将从发布有问题的代码开始:

    public async Task main()
    {
       Task t = func();
       await t;
       list.ItemsSource = jlist; //jlist previously defined
    }


    public async Task func()
    {
        TwitterService service = new TwitterService(_consumerKey, _consumerSecret);
        service.AuthenticateWith(_accessToken, _accessTokenSecret);


        TwitterGeoLocationSearch g = new TwitterGeoLocationSearch(40.758367, -73.982706, 25, 0);


        SearchOptions s = new SearchOptions();
        s.Geocode = g;
        s.Q = "";
        s.Count = 1;
        service.Search(s, (statuses, response) => get_tweets(statuses, response));

    void get_tweets(TwitterSearchResult statuses, TwitterResponse response)
    {
        //unimportant code
        jlist.Add(info);
        System.Diagnostics.Debug.WriteLine("done with get_tweets, jlist created");

    }

我在运行 get_tweets(..) 函数时遇到问题(在我认为不同的线程上),并且任务 t 不像我在主函数中那样等待。基本上,我的问题是 list.Itemsource = jlist 在 get_tweets 函数完成之前运行。有没有人有解决方案或正确的方向来指出我?

4

1 回答 1

2

首先,使用. 创建一个TAP 包装器。所以像:TwitterService.SearchTaskCompletionSource

public static Task<Tuple<TwitterSearchResult, TwitterResponse>> SearchAsync(this TwitterService service, SearchOptions options)
{
  var tcs = new TaskCompletionSource<Tuple<TwitterSearchResult, TwitterResponse>>();
  service.Search(options, (status, response) => tcs.SetResult(Tuple.Create(status, response)));
  return tcs.Task;
}

然后你可以使用它来消费它await

SearchOptions s = new SearchOptions();
s.Geocode = g;
s.Q = "";
s.Count = 1;
var result = await service.SearchAsync(s);
get_tweets(result.Item1, result.Item2);
于 2013-07-05T02:42:42.370 回答