我正在使用以下方法构建标准odata客户端: Microsoft.Data.Services.Client.Portable Windows 8 VS2013
我已经通过授权为项目添加了服务引用(TMALiveData)。现在我想要检索数据。我使用以下代码,但是当我这样做时,我在最后一个循环中得到一个空指针引用。
代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Services.Client;
namespace testLSconWithMSv2
{
public class testLSCon
{
static string mResult;
public static string result { get { return mResult; } }
public static void testREADLiveConnection()
{
Uri tmaLiveDataRoot = new Uri("https://xxx.azurewebsites.net/xxx.svc/");
TMLiveData.TMALiveData mLiveData = new TMLiveData.TMALiveData(tmaLiveDataRoot);
mResult = null;
DataServiceQuery<TMLiveData.JobType> query = (DataServiceQuery<TMLiveData.JobType>)mLiveData.JobTypes.Where(c => c.IsActive == true);
mResult = "Trying to READ the data";
try
{
query.BeginExecute(OnQueryComplete, query);
}
catch (Exception ex)
{
mResult = "Error on beginExecute: " + ex.Message;
}
}
private static void OnQueryComplete(IAsyncResult result)
{
DataServiceQuery<TMLiveData.JobType> query = result as DataServiceQuery<TMLiveData.JobType>;
mResult = "Done!";
try
{
foreach (TMLiveData.JobType jobType in query.EndExecute(result))
{
mResult += jobType.JobType1 + ",";
}
}catch (Exception ex)
{
mResult = "Error looping for items: " + ex.Message;
}
}
}
}
有什么明显的我做错了吗? 我已将该方法基于ms示例:How to Execute Async...
答案 0 :(得分:1)
您收到NullReferenceException
,因为您试图将IAsyncResult
投放到DataServiceQuery<TMLiveData.JobType>
。您需要转换IAsyncResult.AsyncState
:
private static void OnQueryComplete(IAsyncResult result)
{
DataServiceQuery<TMLiveData.JobType> query = (DataServiceQuery<TMLiveData.JobType>) result.AsyncState;
mResult = "Done!";
try
{
foreach (TMLiveData.JobType jobType in query.EndExecute(result))
{
mResult += jobType.JobType1 + ",";
}
}
catch (Exception ex)
{
mResult = "Error looping for items: " + ex.Message;
}
}
在旁注中,我在这里使用了显式转换而不是as
运算符。如果你这样做了,你会得到InvalidCastException
而不是NullReferenceException
,这会让你更容易发现错误。