我在项目中使用 Async CTP 库时遇到问题。这是代码:
书页
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (this.DataContext is BookViewModel)
{
var bookViewModel = this.DataContext as BookViewModel;
bookViewModel.UpdateReviews();
}
}
图书视图模型
public async void UpdateReviews()
{
Reviews.Clear();
IEnumerable<Review> newReviews = null;
try
{
newReviews = await BooksManager.GetBookReviews(this.Book.Sysno, 10, 0);
}
catch (Exception ex)
{
}
if (newReviews != null)
{
foreach (var review in newReviews)
{
Reviews.Add(review);
}
}
}
图书管理员
public static async Task<IEnumerable<Review>> GetBookReviews(string sysno, uint limit, uint offset)
{
if (sysno == null)
throw new ArgumentNullException("sysno");
if (string.IsNullOrWhiteSpace(sysno))
throw new ArgumentException("sysno");
string url = CreateBookReviewsURL(sysno, limit, offset);
var reviews = await DownloadDataAsync<IEnumerable<Review>>(url);
return reviews;
}
public static async Task<T> DownloadDataAsync<T>(string url)
{
if (url == null)
throw new ArgumentNullException("url");
var newUrl = url.Contains("?") ?
string.Format("{0}d={1}", url, DateTime.Now) :
string.Format("{0}?d={1}", url, DateTime.Now); //to avoid caching
string data = null;
WebRequest webRequest = WebRequest.CreateHttp(newUrl);
using (WebResponse response = await webRequest.GetResponseAsync())
{
if (response.Headers["StatusCode"] == "200")
{
using (var stm = response.GetResponseStream())
{
using (var reader = new StreamReader(stm))
{
data = await reader.ReadToEndAsync();
}
}
}
}
var books = await ParseDataAsync<T>(data);
return books;
}
它抛出 NullReferenceException
在 SmartLib.ViewModels.BooksViewModel.d_ 8.MoveNext()
在 System.Runtime.CompilerServices.TaskAwaiter.<>c _DisplayClass5.b__1(Object state) 在 System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, System.Reflection.RuntimeMethodInfo.InternalInvoke(对象 obj,BindingFlags invokeAttr,BindingFlags 绑定器,Object[] 参数,CultureInfo 文化,StackCrawlMark 和 stackMark)上的 Binder 活页夹、对象参数、CultureInfo 文化、布尔 isBinderDefault、程序集调用者、布尔验证访问、StackCrawlMark 和 stackMark)在 System.Reflection.MethodBase.Invoke(对象 obj,对象 [] 参数)
在 System.Delegate.DynamicInvokeOne(Object[] args) 在 System.MulticastDelegate.DynamicInvokeImpl(Object[] args) 在 System.Delegate.DynamicInvoke(Object[] args) 在 System.Windows.Threading.DispatcherOperation.Invoke() 在 System .Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority) 在 System.Windows.Threading.Dispatcher.OnInvoke(Object context) 在 System.Windows.Hosting.CallbackCookie.Invoke(Object[] args) 在 System.Windows.Hosting.DelegateWrapper System.Windows.RuntimeHost.ManagedHost.InvokeDelegate 处的.InternalInvoke(Object[] args)
(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
在 App.xaml.cs 中调用 BooksManager.GetBookReviews() 可以正常工作。