irpas技术客

【原创】C#List线程安全相关解决方案_赵庆明老师_c# list 线程安全

未知 1269

在多线程程序中,可能多个线程都需要操作一个共用的List,而微软实现的List却是非线程安全的。也就是说,在多线程情况下,共用的List会产生线程安全问题。

对于这个问题,有不少的解决方案,比如换用线程安全的类型,如:

BlockingCollection<T> ConcurrentBag<T> ConcurrentDictionary<TKey,TValue> ConcurrentQueue<T> ConcurrentStack<T> OrderablePartitioner<TSource> Partitioner Partitioner<TSource>

且在MSDN上有相关额介绍: https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.concurrent?view=net-6.0

但是,你会发现一个严重的问题,缺少删除(remove)。这样往往不是我们想要的。

最简单的是,用lock锁。这里有两种使用方法

第一种:

private static List<WxOAuth2Model> wxOAuth2 = new List<WxOAuth2Model>(); public void Test() { lock(wxOAuth2 ) { //对于wxOAuth2 进行读取,添加,删除 } }

这种方案最为常见,副作用暂未研究。

第二种:

private static List<WxOAuth2Model> wxOAuth2 = new List<WxOAuth2Model>(); public void Test() { lock ((wxOAuth2 as ICollection).SyncRoot) { //对于wxOAuth2 进行读取,添加,删除 } }

将对象转换成ICollection接口类型,然后对这个接口的SyncRoot进行lock。 这种方案,在MSDN上有相关的介绍 https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.icollection.syncroot

鼠标点击SyncRoot,按F12,得到ICollection的定义

public interface ICollection : IEnumerable { int Count { get; } bool IsSynchronized { get; } object SyncRoot { get; } void CopyTo(Array array, int index); }

其中包含一个只读的object 类型的SyncRoot属性。

鼠标点击List中的list,按F12,会得到这个List的定义:

public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList { }

从定义中可知,List继承(实现)了ICollection接口,因此将该List转换为ICollection后,就可以访问其SyncRoot 属性。

再看一下Dictionary的实现

public class Dictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IReadOnlyDictionary<TKey, TValue>, ICollection, IDictionary, IDeserializationCallback, ISerializable where TKey : notnull { }

同样实现了ICollection接口,因此Dictionary也可以按照同样的方法进行锁定,以实现线程安全的操作。

与集合相关的,MSDN上亦有介绍: https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.icollection?view=net-6.0

可以如此操作的,罗列了一大堆,看看有么有你想要的?

派生 Microsoft.Build.BuildEngine.ToolsetCollection Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Extensions.DependencyInjection.ServiceCollection Microsoft.Extensions.Primitives.StringValues System.Activities.Hosting.SymbolResolver System.Activities.Presentation.Model.ModelItemCollection System.Activities.Presentation.Model.ModelItemDictionary System.Activities.Presentation.Toolbox.ToolboxCategoryItems System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue> System.Collections.Generic.Dictionary<TKey,TValue> System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection System.Collections.Generic.HashSet<T> System.Collections.Generic.IDictionary<TKey,TValue> System.Collections.Generic.IList<T> System.Collections.Generic.ISet<T> System.Collections.Generic.LinkedList<T> System.Collections.Generic.List<T> System.Collections.Generic.SortedDictionary<TKey,TValue> System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection System.Collections.Generic.SortedDictionary<TKey,TValue>.ValueCollection System.Collections.Generic.SortedList<TKey,TValue> System.Collections.Generic.SortedSet<T> System.Collections.Generic.SynchronizedCollection<T> System.Collections.Generic.SynchronizedReadOnlyCollection<T> System.Collections.Immutable.ImmutableArray<T> System.Collections.Immutable.ImmutableArray<T>.Builder System.Collections.Immutable.ImmutableDictionary<TKey,TValue> System.Collections.Immutable.ImmutableDictionary<TKey,TValue>.Builder System.Collections.Immutable.ImmutableHashSet<T> System.Collections.Immutable.ImmutableHashSet<T>.Builder System.Collections.Immutable.ImmutableList<T> System.Collections.Immutable.ImmutableList<T>.Builder System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue> System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue>.Builder System.Collections.Immutable.ImmutableSortedSet<T> System.Collections.Immutable.ImmutableSortedSet<T>.Builder System.Collections.ObjectModel.Collection<T> System.Collections.ObjectModel.ReadOnlyCollection<T> System.Collections.ObjectModel.ReadOnlyDictionary<TKey,TValue> System.Collections.ObjectModel.ReadOnlyDictionary<TKey,TValue>.KeyCollection System.Collections.ObjectModel.ReadOnlyDictionary<TKey,TValue>.ValueCollection System.Data.Linq.ChangeConflictCollection System.Data.Linq.EntitySet<TEntity> System.Data.Objects.DataClasses.EntityCollection<TEntity> System.Data.Objects.ObjectParameterCollection System.Diagnostics.ActivityTagsCollection System.DirectoryServices.AccountManagement.PrincipalCollection System.DirectoryServices.AccountManagement.PrincipalValueCollection<T> System.Dynamic.ExpandoObject System.IO.Log.ReservationCollection System.Json.JsonArray System.Json.JsonObject System.Net.Http.Headers.HttpHeaderValueCollection<T> System.Net.Http.HttpRequestOptions System.Net.HttpListenerPrefixCollection System.Net.NetworkInformation.GatewayIPAddressInformationCollection System.Net.NetworkInformation.IPAddressCollection System.Net.NetworkInformation.IPAddressInformationCollection System.Net.NetworkInformation.MulticastIPAddressInformationCollection System.Net.NetworkInformation.UnicastIPAddressInformationCollection System.Runtime.CompilerServices.ReadOnlyCollectionBuilder<T> System.Security.Principal.IdentityReferenceCollection System.ServiceModel.Channels.MessageProperties System.ServiceModel.Configuration.CustomBindingElement System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> System.ServiceModel.Dispatcher.IMessageFilterTable<TFilterData> System.ServiceModel.Dispatcher.MessageFilterTable<TFilterData> System.ServiceModel.Dispatcher.MessageQueryTable<TItem> System.ServiceModel.Dispatcher.XPathMessageFilterTable<TFilterData> System.ServiceModel.ExtensionCollection<T> System.ServiceModel.IExtensionCollection<T> System.Speech.Recognition.SemanticValue System.Web.ModelBinding.ModelBinderDictionary System.Web.ModelBinding.ModelStateDictionary System.Windows.Controls.ColumnDefinitionCollection System.Windows.Controls.RowDefinitionCollection System.Windows.Data.XmlNamespaceMappingCollection System.Windows.Documents.TableCellCollection System.Windows.Documents.TableColumnCollection System.Windows.Documents.TableRowCollection System.Windows.Documents.TableRowGroupCollection System.Windows.Documents.TextElementCollection<TextElementType> System.Windows.Forms.NumericUpDownAccelerationCollection System.Windows.FreezableCollection<T> System.Windows.Markup.INameScopeDictionary System.Windows.Media.Animation.ClockCollection System.Windows.Media.Animation.TimelineCollection System.Windows.Media.CharacterMetricsDictionary System.Windows.Media.DoubleCollection System.Windows.Media.DrawingCollection System.Windows.Media.Effects.BitmapEffectCollection System.Windows.Media.FamilyTypefaceCollection System.Windows.Media.FontFamilyMapCollection System.Windows.Media.GeneralTransformCollection System.Windows.Media.GeometryCollection System.Windows.Media.GradientStopCollection System.Windows.Media.Int32Collection System.Windows.Media.LanguageSpecificStringDictionary System.Windows.Media.Media3D.GeneralTransform3DCollection System.Windows.Media.Media3D.MaterialCollection System.Windows.Media.Media3D.Model3DCollection System.Windows.Media.Media3D.Point3DCollection System.Windows.Media.Media3D.Transform3DCollection System.Windows.Media.Media3D.Vector3DCollection System.Windows.Media.Media3D.Visual3DCollection System.Windows.Media.PathFigureCollection System.Windows.Media.PathSegmentCollection System.Windows.Media.PointCollection System.Windows.Media.TextEffectCollection System.Windows.Media.TransformCollection System.Windows.Media.VectorCollection System.Windows.TextDecorationCollection System.Windows.TriggerActionCollection System.Workflow.Activities.OperationParameterInfoCollection System.Workflow.ComponentModel.ActivityCollection System.Xml.Xsl.Runtime.XmlQueryNodeSequence System.Xml.Xsl.Runtime.XmlQuerySequence<T>


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #C #list #线程安全