6

I have an application that has a list of objects stored in a static ConcurrentBag.

The UI has a timer that runs methods that can update the objects in the ConcurrentBag.

Only one thread (Started by the timer) will try to update these objects. However, this thread will enumerate through the list and then update the items as it goes.

At the same time these objects can be read by the UI thread.

ConcurrentBag is working perfectly for what I want to do. All the business logic is in a separate project and I now need to port everything to iOS and Android. I'm doing this with Xamarin and so am converting the business logic into a Portable Class Library.

Although everything I'm targeting appears to support ConcurrentBag, when I try to access it in a PCL, System.Collections.Concurrent is not available. Even if I only target .net 4.5 and above + windows store apps (Both of which I have used ConcurrentBags for)

Is there another alternative to ConcurrentBag or am I better off just creating separate projects for each targeted system?

7
  • Which VS version are you using, and which PCL targets do you select? If I for example select .NET 4, Windows (Store apps) 8, Xamarin.Android and Xamarin.iOS in VS2013 Update 2RC, I can successfully employ ConcurrentBag in my code. As long as you don't target Windows Phone or Silverlight, I think you should have no problems using ConcurrentBag in your PCL. Apr 29, 2014 at 7:06
  • Thanks Anders. I'm currently on Update 1 so I'm downloading update 2 now to see if it helps. Is it all versions of Win Phone that won't work?
    – Oli
    Apr 29, 2014 at 8:43
  • I just checked; System.Collections.Concurrent namespace is not included in any WP version, including 8.1. By the way, it seems odd that you cannot access ConcurrentBag on VS 2013 Update 1 as long as you avoid the WP/Silverlight targets? Have you double-checked that it is not working on Update 1 even when you target .NET 4, Windows (Store) 8, Xamarin.Android and Xamarin.iOS? Apr 29, 2014 at 8:51
  • Yes I thought it strange. Maybe I was doing something else wrong as well but I only had Win Store and .net 4.5 + selected and couldn't see it. Do you have a link where I can check what I can use with PCL as msdn.microsoft.com/en-us/library/dd381779(v=vs.110).aspx states that I can use ConcurrentBag in Win Phone (I guess just not via a PCL?)
    – Oli
    Apr 29, 2014 at 8:58
  • I tried to include WP 8.1 in my PCL, and then the IDE could not "see" ConcurrentBag, so I assume that at least in (the current) PCL set-up you will not be able to include WP 8.1 target. Regarding documentation, I checked the list of namespaces here. Of course, I am not 100% sure that this list is up-to-date. Apr 29, 2014 at 9:13

1 Answer 1

1

Well, if the obvious won't work, you have several options here. First, is to decompile ConcurrentBag and use that code. Second, is to come up with a replacement. It's my estimate that you in your specific case don't necessarily need the performance guarantees and ordering issues of a ConcurrentBag... So, this is a working example of what would fit your bill:

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";
                                               }
                                           }
                                       });
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.