我有一个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()时返回值的方法是什么。
答案 0 :(得分: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()
答案 1 :(得分:-1)
您应该从bHttpsCompleted函数返回。