0

我有一个 ScheduledTaskAgent 项目,ScheduledAgent.cs 中的 oninvoke() 方法调用自定义类库项目中的 fetchcurrentdetails() 方法。

在这个公共字符串 fetchcurrentdetails() 方法中,它有以下一系列事件。

            //class variables
            string strAddress = string.empty;
             public string fetchcurrentdetails()
              {
                GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
                if (watcher.Permission == GeoPositionPermission.Granted)
                 {
                  watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);    
                 }
                 return strAddress ;
              }

           private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
             {
            WebClient bWC = new WebClient();                
            System.Uri buri = new Uri("http://dev.virtual//...");
            bWC.DownloadStringAsync(new Uri(buri.ToString()));
            bWC.DownloadStringCompleted += new                    DownloadStringCompletedEventHandler(bHttpsCompleted);
           }


          private void bHttpsCompleted(object sender, DownloadStringCompletedEventArgs bResponse)
              {
             //do some data extraction and return the string
             strAddress = "This is extracted data";
             }

return 语句总是将空字符串返回给调用语句。知道如何确保执行保留在类库中,直到方法/事件 bHttpsCompleted() 完成?或者当事件/方法 bHttpsCompleted() 被触发时返回值的方式是什么。

4

2 回答 2

2

你可以这样修改

public Task<string> fetchcurrentdetails()
    {

        var tcs = new TaskCompletionSource<string>();

        GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
        if (watcher.Permission == GeoPositionPermission.Granted)
        {
            watcher.PositionChanged += (s, e) =>
                {
                    WebClient bWC = new WebClient();
                    System.Uri buri = new Uri("http://dev.virtual//...");
                    bWC.DownloadStringAsync(new Uri(buri.ToString()));
                    bWC.DownloadStringCompleted += (s1, e1) =>
                    {

                        if (e1.Error != null) tcs.TrySetException(e1.Error);
                        else if (e1.Cancelled) tcs.TrySetCanceled();
                        else
                            tcs.TrySetResult(e1.Result);
                        //do some data extraction and return the string                          
                    };
                };
        }
        return tcs.Task;
    }

称呼 :await fetchcurrentdetails()

于 2012-12-07T13:22:26.050 回答
-1

您应该从 bHttpsCompleted 函数返回。

于 2012-12-05T13:38:28.927 回答