JsonConvert.DeserializeObject和ThreadAbortedException

时间:2017-08-08 16:08:38

标签: c# json xamarin json.net task

在Xamarin项目中,我有以下代码的PCL库。

我们定义ConcurrentQueue<SyncRequest>。对于初始化对象初始化,已附加消费者Task

_syncConsumer = new Task(
                ProcessSyncQueue,
                _syncConsumerCancellationTokenSource.Token);
_syncConsumer.Start();

ProcessSyncQueue方法扫描同步队列并调用GetSyncableEntity方法:

private async void ProcessSyncQueue()
{
    while (true)
    {
         SyncRequest syncRequest;
         if (_syncQueue.TryDequeue(out syncRequest))
         {
             var syncableEntity = GetSyncableEntity(syncRequest);
         }
    }
}

GetSyncableEntity依次执行Json反序列化:

private T GetSyncableEntity(SyncRequest syncRequest)
{
    T syncableEntity = default(T);

    try
    {
       syncableEntity = JsonConvert.DeserializeObject<T>(syncRequest.SynchronizationContent);
    }
    catch (Exception e)
    {

    }

    return syncableEntity;
 }

在此步骤中,我们会收到ThreadAbortedException,其中“线程正在中止”&#39;信息。 堆栈跟踪:

   at Newtonsoft.Json.JsonTextReader.FinishReadStringIntoBuffer(Int32 charPos, Int32 initialPosition, Int32 lastWritePosition)
   at Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer(Char quote)
   at Newtonsoft.Json.JsonTextReader.ParseProperty()
   at Newtonsoft.Json.JsonTextReader.ParseObject()
   at Newtonsoft.Json.JsonTextReader.Read()
   at Newtonsoft.Json.JsonReader.ReadAndAssert()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)

任何人都可以帮助我们了解正在发生的事情以及如何对其进行反序列化吗?

更新: 我发布了更多代码,因为审核人员建议我删除CancellationTokenSource,使用Task.Run初始化消费者,await。 并创建了一些像这样的测试实现:

    protected void RequestSynchronizationFor(
        string synchronizationKey,
        T entity)
    {
        if (!_isInitialized)
        {
            InitializeSyncRequestsQueue();
        }

        _syncQueue.Enqueue(GetSyncRequest(synchronizationKey, entity));
    }

因此我们请求实体同步调用RequestSynchronizationFor方法。如果是冷运行,我们从db调用InitializeSyncRequestsQueue初始化队列并等待Task.Run消费者线程。

    private async void InitializeSyncRequestsQueue()
    {
        var syncRequests = GetSyncedRequests();

        foreach (var syncRequest in syncRequests)
        {
            _syncQueue.Enqueue(syncRequest);
        }

        await Task.Run(ProcessSyncQueue);
    }

以前的消费者任务也做同样的事情:

 private async Task ProcessSyncQueue()
    {
        while (true)
        {
            SyncRequest syncRequest;
            if (_syncQueue.TryDequeue(out syncRequest))
            {
                var syncableEntity = GetSyncableEntity(syncRequest);
            }
        }
    }

仍然有同样的例外。不确定它是否合理,但我正在运行单元测试中的代码。有什么建议吗?

UPDATE2:

我做了更改后发布了第一个&#39; UPDATE&#39;,调用堆栈也发生了一些变化:

   at Newtonsoft.Json.JsonSerializer.get_MetadataPropertyHandling()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)

更新3: 我在假服务中提取所有代码,并且在尝试反序列化时仍然有相同的异常:

public class JsonDeserializeService<T>
{
    private readonly bool _isInitialized;

    private readonly ConcurrentQueue<SyncRequest> _syncQueue;

    public JsonDeserializeService()
    {
        _isInitialized = false;
        _syncQueue = new ConcurrentQueue<SyncRequest>();
    }

    public void RequestSynchronizationFor(
        string synchronizationKey,
        T entity)
    {
        if (!_isInitialized)
        {
            InitializeSyncRequestsQueue();
        }

        _syncQueue.Enqueue(GetSyncRequest(synchronizationKey, entity));
    }

    private async void InitializeSyncRequestsQueue()
    {
        var syncRequests = Enumerable.Empty<SyncRequest>();

        foreach (var syncRequest in syncRequests)
        {
            _syncQueue.Enqueue(syncRequest);
        }

        await Task.Run(ProcessSyncQueue);
    }

    private async Task ProcessSyncQueue()
    {
        while (true)
        {
            SyncRequest syncRequest;
            if (_syncQueue.TryDequeue(out syncRequest))
            {
                var syncableEntity = GetSyncableEntity(syncRequest);
            }
        }
    }

    private T GetSyncableEntity(SyncRequest syncRequest)
    {
        T syncableEntity = default(T);

        try
        {
            syncableEntity = JsonConvert.DeserializeObject<T>(syncRequest.SynchronizationContent);
        }
        catch (Exception e)
        {
        }

        return syncableEntity;
    }

    private SyncRequest GetSyncRequest(string synchronizationKey, T entity)
    {
        return new SyncRequest()
        {
            SynchronizationContent = JsonConvert.SerializeObject(entity),
            SynchronizationDelayUntil = DateTime.Now
        };
    }
}

从单元测试中触发:

    public void Syncable_Service_Should_Not_Generate_Exception()
    {
        var syncService = new JsonDeserializeService<FakeSyncableEntity>();
        syncService.RequestSynchronizationFor("syncKey", new FakeSyncableEntity() { Content = "Content" });
    }

1 个答案:

答案 0 :(得分:2)

这种行为的原因非常简单。 您的测试比异步任务更早结束。当测试结束时,它会为子线程引发ThreadAbortException。

您需要调用task.Wait()以使主线程等待任务完成。