Improve JSON deserialization and observable collection handling

- Add batch update support for IAcObservableCollection during deserialization to suppress per-item notifications and fire a single reset event.
- Throw AcJsonDeserializationException with a clear message if a type lacks a parameterless constructor during deserialization.
- Enhance IsGenericCollectionType to recognize more collection types, including ObservableCollection<T> and custom IList<T> implementations.
- Improve array and collection deserialization logic to better handle target types and fall back to List<T> if needed.
- In AcObservableCollection, catch and ignore ObjectDisposedException in event handlers to prevent errors from disposed subscribers.
- Remove redundant batch update logic from AcSignalRDataSource; rely on deserializer's handling.
- Set SkipNegotiation = true in SignalR client options for WebSockets-only optimization and comment out automatic HubConnection.StartAsync() for more controlled connection management.
This commit is contained in:
Loretta 2025-12-11 23:46:30 +01:00
parent c29b3daa0e
commit 8e7869b3da
4 changed files with 182 additions and 71 deletions

View File

@ -5,6 +5,7 @@ using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text.Json; using System.Text.Json;
using AyCode.Core.Helpers;
using AyCode.Core.Interfaces; using AyCode.Core.Interfaces;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -308,7 +309,27 @@ public static class AcJsonDeserializer
} }
var metadata = GetTypeMetadata(targetType); var metadata = GetTypeMetadata(targetType);
var instance = metadata.CompiledConstructor?.Invoke() ?? Activator.CreateInstance(targetType);
object? instance;
if (metadata.CompiledConstructor != null)
{
instance = metadata.CompiledConstructor.Invoke();
}
else
{
try
{
instance = Activator.CreateInstance(targetType);
}
catch (MissingMethodException ex)
{
throw new AcJsonDeserializationException(
$"Cannot deserialize type '{targetType.FullName}' because it does not have a parameterless constructor. " +
$"Add a parameterless constructor or use a different serialization approach.",
null, targetType, ex);
}
}
if (instance == null) return null; if (instance == null) return null;
if (element.TryGetProperty("$id", out var idElement)) if (element.TryGetProperty("$id", out var idElement))
@ -425,9 +446,15 @@ public static class AcJsonDeserializer
private static void PopulateList(JsonElement arrayElement, IList targetList, Type listType, DeserializationContext context) private static void PopulateList(JsonElement arrayElement, IList targetList, Type listType, DeserializationContext context)
{ {
var elementType = GetListElementType(listType); var elementType = GetCollectionElementType(listType);
if (elementType == null) return; if (elementType == null) return;
// Use batch update for IAcObservableCollection to suppress per-item notifications
var acObservable = targetList as IAcObservableCollection;
acObservable?.BeginUpdate();
try
{
targetList.Clear(); targetList.Clear();
foreach (var item in arrayElement.EnumerateArray()) foreach (var item in arrayElement.EnumerateArray())
@ -439,6 +466,11 @@ public static class AcJsonDeserializer
} }
} }
} }
finally
{
acObservable?.EndUpdate();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static object? ReadArray(JsonElement element, Type targetType, DeserializationContext context) private static object? ReadArray(JsonElement element, Type targetType, DeserializationContext context)
@ -446,21 +478,55 @@ public static class AcJsonDeserializer
var elementType = GetCollectionElementType(targetType); var elementType = GetCollectionElementType(targetType);
if (elementType == null) return null; if (elementType == null) return null;
// For arrays, we need to use a temporary list
if (targetType.IsArray)
{
var list = GetOrCreateListFactory(elementType)(); var list = GetOrCreateListFactory(elementType)();
foreach (var item in element.EnumerateArray()) foreach (var item in element.EnumerateArray())
{ {
list.Add(ReadValue(item, elementType, context)); list.Add(ReadValue(item, elementType, context));
} }
if (targetType.IsArray)
{
var array = Array.CreateInstance(elementType, list.Count); var array = Array.CreateInstance(elementType, list.Count);
list.CopyTo(array, 0); list.CopyTo(array, 0);
return array; return array;
} }
return list; // Try to create an instance of the target collection type directly
// This handles ObservableCollection<T>, AcObservableCollection<T>, etc.
IList? targetList = null;
try
{
var instance = Activator.CreateInstance(targetType);
if (instance is IList list)
{
targetList = list;
}
}
catch
{
// Fallback to List<T> if we can't create the target type
}
// Fallback to List<T> if target type couldn't be instantiated
targetList ??= GetOrCreateListFactory(elementType)();
// Use batch update for IAcObservableCollection to suppress per-item notifications
var acObservable = targetList as IAcObservableCollection;
acObservable?.BeginUpdate();
try
{
foreach (var item in element.EnumerateArray())
{
targetList.Add(ReadValue(item, elementType, context));
}
}
finally
{
acObservable?.EndUpdate();
}
return targetList;
} }
private static void MergeIIdCollection(JsonElement arrayElement, object existingCollection, PropertySetterInfo propInfo, DeserializationContext context) private static void MergeIIdCollection(JsonElement arrayElement, object existingCollection, PropertySetterInfo propInfo, DeserializationContext context)
@ -472,6 +538,12 @@ public static class AcJsonDeserializer
var existingList = (IList)existingCollection; var existingList = (IList)existingCollection;
var count = existingList.Count; var count = existingList.Count;
// Use batch update for IAcObservableCollection to suppress per-item notifications
var acObservable = existingList as IAcObservableCollection;
acObservable?.BeginUpdate();
try
{
Dictionary<object, object>? existingById = null; Dictionary<object, object>? existingById = null;
if (count > 0) if (count > 0)
{ {
@ -515,6 +587,11 @@ public static class AcJsonDeserializer
if (newItem != null) existingList.Add(newItem); if (newItem != null) existingList.Add(newItem);
} }
} }
finally
{
acObservable?.EndUpdate();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static object? ReadPrimitive(JsonElement element, Type targetType, JsonValueKind valueKind) private static object? ReadPrimitive(JsonElement element, Type targetType, JsonValueKind valueKind)
@ -1038,18 +1115,43 @@ public static class AcJsonDeserializer
} }
/// <summary> /// <summary>
/// Check if type is a generic collection type (List, IList, etc.) /// Check if type is a generic collection type (List, IList, ObservableCollection, etc.)
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsGenericCollectionType(Type type) private static bool IsGenericCollectionType(Type type)
{ {
if (!type.IsGenericType) return false; if (!type.IsGenericType)
{
// Check if it implements IList<T> interface (covers ObservableCollection<T> subclasses)
foreach (var iface in type.GetInterfaces())
{
if (iface.IsGenericType && iface.GetGenericTypeDefinition() == typeof(IList<>))
return true;
}
return false;
}
var genericDef = type.GetGenericTypeDefinition(); var genericDef = type.GetGenericTypeDefinition();
return genericDef == typeof(List<>) ||
// Check common collection types
if (genericDef == typeof(List<>) ||
genericDef == typeof(IList<>) || genericDef == typeof(IList<>) ||
genericDef == typeof(ICollection<>) || genericDef == typeof(ICollection<>) ||
genericDef == typeof(IEnumerable<>); genericDef == typeof(IEnumerable<>) ||
genericDef == typeof(System.Collections.ObjectModel.ObservableCollection<>) ||
genericDef == typeof(System.Collections.ObjectModel.Collection<>))
{
return true;
}
// Check if it implements IList<T> interface (covers AcObservableCollection<T> and similar)
foreach (var iface in type.GetInterfaces())
{
if (iface.IsGenericType && iface.GetGenericTypeDefinition() == typeof(IList<>))
return true;
}
return false;
} }
#endregion #endregion
} }

View File

@ -374,18 +374,30 @@ namespace AyCode.Core.Helpers
protected override void OnPropertyChanged(PropertyChangedEventArgs e) protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{ {
if (IsUpdating) if (IsUpdating) return;
return;
try
{
base.OnPropertyChanged(e); base.OnPropertyChanged(e);
} }
catch (ObjectDisposedException)
{
// A feliratkozott komponens már Disposed - biztonságosan figyelmen kívül hagyjuk
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{ {
if (IsUpdating) if (IsUpdating) return;
return;
try
{
base.OnCollectionChanged(e); base.OnCollectionChanged(e);
} }
catch (ObjectDisposedException)
{
// A feliratkozott komponens már Disposed - biztonságosan figyelmen kívül hagyjuk
}
}
} }
} }

View File

@ -353,13 +353,9 @@ namespace AyCode.Services.Server.SignalRs
{ {
if (!setSourceToWorkingReferenceList) if (!setSourceToWorkingReferenceList)
{ {
if (InnerList is IAcObservableCollection observable) // CopyTo uses JSON serialization which already handles BeginUpdate/EndUpdate
{ // for IAcObservableCollection via AcJsonDeserializer.Populate
observable.BeginUpdate();
fromSource.CopyTo(InnerList); fromSource.CopyTo(InnerList);
observable.EndUpdate();
}
else fromSource.CopyTo(InnerList);
} }
else else
{ {

View File

@ -46,6 +46,7 @@ namespace AyCode.Services.SignalRs
options.TransportMaxBufferSize = 30_000_000; //Increasing this value allows the client to receive larger messages. default: 65KB; unlimited: 0;; options.TransportMaxBufferSize = 30_000_000; //Increasing this value allows the client to receive larger messages. default: 65KB; unlimited: 0;;
options.ApplicationMaxBufferSize = 30_000_000; //Increasing this value allows the client to send larger messages. default: 65KB; unlimited: 0; options.ApplicationMaxBufferSize = 30_000_000; //Increasing this value allows the client to send larger messages. default: 65KB; unlimited: 0;
options.CloseTimeout = TimeSpan.FromSeconds(10); //default: 5 sec. options.CloseTimeout = TimeSpan.FromSeconds(10); //default: 5 sec.
options.SkipNegotiation = true; // Skip HTTP negotiation when using WebSockets only
//options.AccessTokenProvider = null; //options.AccessTokenProvider = null;
//options.HttpMessageHandlerFactory = null; //options.HttpMessageHandlerFactory = null;
@ -82,7 +83,7 @@ namespace AyCode.Services.SignalRs
_ = HubConnection.On<int, byte[], int?>(nameof(IAcSignalRHubClient.OnReceiveMessage), OnReceiveMessage); _ = HubConnection.On<int, byte[], int?>(nameof(IAcSignalRHubClient.OnReceiveMessage), OnReceiveMessage);
//_ = HubConnection.On<int, int>(nameof(IAcSignalRHubClient.OnRequestMessage), OnRequestMessage); //_ = HubConnection.On<int, int>(nameof(IAcSignalRHubClient.OnRequestMessage), OnRequestMessage);
HubConnection.StartAsync().Forget(); //HubConnection.StartAsync().Forget();
} }
/// <summary> /// <summary>