c# - 可移植类库中的 ConcurrentBag 替代方案

标签 c# .net multithreading portable-class-library

我有一个应用程序,它有一个存储在 static ConcurrentBag 中的对象列表。

UI 有一个计时器,它运行的方法可以更新 ConcurrentBag 中的对象。

只有一个线程(由计时器启动)会尝试更新这些对象。但是,此线程将枚举列表,然后更新项目。

同时这些对象可以被UI线程读取。

ConcurrentBag 非常适合我想做的事情。所有业务逻辑都在一个单独的项目中,我现在需要将所有内容移植到 iOS 和 Android。我正在使用 Xamarin 执行此操作,因此我将业务逻辑转换为可移植类库

虽然我的所有目标似乎都支持 ConcurrentBag,但当我尝试在 PCL 中访问它时,System.Collections.Concurrent不可用。即使我只针对 .net 4.5 及更高版本 + Windows 应用商店应用(我都使用了 ConcurrentBags)

ConcurrentBag 是否有另一种选择,还是我最好只为每个目标系统创建单独的项目?

最佳答案

好吧,如果显而易见的方法行不通,您有多种选择。首先,是反编译 ConcurrentBag 并使用该代码。其次,是想出一个替代品。据我估计,在您的特定情况下,您不一定需要 ConcurrentBag 的性能保证和订购问题......因此,这是一个适合您的账单的工作示例:

namespace Naive
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;

    public class ThreadSafeCollectionNaive<T>
    {
        private readonly List<T> _list = new List<T>();
        private readonly object _criticalSection = new object();

        /// <summary>
        /// This is consumed in the UI. This is O(N)
        /// </summary>
        public ReadOnlyCollection<T> GetContentsCopy()
        {
            lock (_criticalSection)
            {
                return new List<T>(_list).AsReadOnly();
            }
        }

        /// <summary>
        /// This is a hacky way to handle updates, don't want to write lots of code
        /// </summary>
        public void Update(Action<List<T>> workToDoInTheList)
        {
            if (workToDoInTheList == null) throw new ArgumentNullException("workToDoInTheList");

            lock (_criticalSection)
            {
                workToDoInTheList.Invoke(_list);
            }
        }

        public int Count
        {
            get
            {
                lock (_criticalSection)
                {
                    return _list.Count;
                }
            }
        }

        // Add more members as you see fit
    }

    class Program
    {
        static void Main(string[] args)
        {
            var collectionNaive = new ThreadSafeCollectionNaive<string>();

            collectionNaive.Update((l) => l.AddRange(new []{"1", "2", "3"}));

            collectionNaive.Update((l) =>
                                       {
                                           for (int i = 0; i < l.Count; i++)
                                           {
                                               if (l[i] == "1")
                                               {
                                                   l[i] = "15";
                                               }
                                           }
                                       });
        }
    }
}

关于c# - 可移植类库中的 ConcurrentBag 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346880/

相关文章:

java 从另一个线程更新 UI 组件

java - 简单的数据线程问题-java

c - linux pthread 在指定时间循环运行(避免信号)

C# listview 添加项目

.net - 使用 C# 中的文件路径复制文件夹中的文件

c# - MemoryStream (pdf) 到 Ghostscript 到 MemoryStream (jpg)

c# - 无法从 Microsoft.Extensions.Logging 解析 ILogger

c# - ASP.Net TableHeaderRow Controller 产生 tr 而不是 th

c# - 有没有一种简单的方法将事件与 ListViewItem 关联?

c# - 使用HttpClient分块上传大文件到Controller,IFormFile总是为空