在c# .net中使用BeginExecute异步访问wcf服务出错



我正在构建一个标准的odata客户端,使用:Microsoft.Data.Services.Client.PortableWindows 8VS2013

我已经授权给项目(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;
            }

        }
    }
}

有什么明显的我做错了吗?

如何执行异步…

您正在获得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,这将使您更容易发现错误。

最新更新