Example #1
0
        public void SynchronizedListUnitTest()
        {
            SynchronizedList<string> list = new SynchronizedList<string>();

            list.Add("one");
            list.Add("two");
            Assert.IsTrue(list.Count == 2);

            foreach (string name in list)
            {
                Assert.IsTrue(list.Contains(name));
            }

            list.Remove("one");
            Assert.IsTrue(list.Count == 1);

            list.Insert(0, "one");
            Assert.IsTrue(list.Count == 2);
            Assert.IsTrue(list.Contains("one"));
            Assert.IsTrue(list[0] == "one");

            list.RemoveAt(0);
            Assert.IsFalse(list.Contains("one"));

            list.Clear();
            Assert.IsTrue(list.Count == 0);
        }
		/// <summary>
		/// Создать <see cref="DdeColumnsPicker"/>.
		/// </summary>
		public DdeColumnsPicker()
		{
			InitializeComponent();

			lsvColumnsAll.ItemsSource = _columnsAll;
			lsvColumnsSelected.ItemsSource = _columnsSelected;

			ExcludeColumns = new SynchronizedList<string>();
		}
        public void TestRemoveAt()
        {
            SynchronizedList <int> list = new SynchronizedList <int>(new List <int>(), new IgnoreLocking());

            list.Insert(0, 1);
            list.Insert(0, 2);
            list.Insert(0, 3);
            list.RemoveAt(1);
            list.RemoveAt(0);

            Assert.AreEqual(1, list.Count);
            Assert.AreEqual(1, list[0]);
        }
Example #4
0
 public void SynchronizedListAddTest()
 {
     tlog.Debug(tag, $"SynchronizedListAddTest START");
     try
     {
         var sl = new SynchronizedList <int>();
         Assert.IsNotNull(sl, "null SynchronizedList");
         sl.Add(1);
     }
     catch (Exception e)
     {
         Assert.Fail("Caught Exception" + e.ToString());
     }
     tlog.Debug(tag, $"SynchronizedListAddTest END");
 }
Example #5
0
        public void TriggerConstructor()
        {
            tlog.Debug(tag, $"TriggerConstructor START");

            try
            {
                var sl = new SynchronizedList <int>();

                Assert.IsNotNull(sl, "null SynchronizedList");
                Assert.IsInstanceOf <SynchronizedList <int> >(sl, "Should return SynchronizedList instance.");
            }
            catch (Exception e)
            {
                Assert.Fail("Caught Exception" + e.ToString());
            }

            tlog.Debug(tag, $"TriggerConstructor END");
        }
        public void TestIndexer()
        {
            SynchronizedList <int> list = new SynchronizedList <int>(new List <int>(), new IgnoreLocking());

            list.Insert(0, 1);
            list.Insert(0, 2);
            list.Insert(0, 3);

            Assert.AreEqual(3, list[0]);
            Assert.AreEqual(2, list[1]);
            Assert.AreEqual(1, list[2]);

            list[2] ^= list[0];
            list[0] ^= list[2];
            list[2] ^= list[0];

            Assert.AreEqual(1, list[0]);
            Assert.AreEqual(2, list[1]);
            Assert.AreEqual(3, list[2]);
        }
        public override void Entry(IModHelper helper)
        {
            IMultiplayerApi multiplayerApi = this.GetCoreApi().GetMultiplayerApi();

            // Sync all the levels
            this.SyncLevel(multiplayerApi, "combatLevel", () => Game1.player.combatLevel.Value, n => Game1.player.combatLevel.Value       = n);
            this.SyncLevel(multiplayerApi, "farmingLevel", () => Game1.player.farmingLevel.Value, n => Game1.player.farmingLevel.Value    = n);
            this.SyncLevel(multiplayerApi, "fishingLevel", () => Game1.player.fishingLevel.Value, n => Game1.player.fishingLevel.Value    = n);
            this.SyncLevel(multiplayerApi, "foragingLevel", () => Game1.player.foragingLevel.Value, n => Game1.player.foragingLevel.Value = n);
            this.SyncLevel(multiplayerApi, "miningLevel", () => Game1.player.miningLevel.Value, n => Game1.player.miningLevel.Value       = n);
            this.SyncLevel(multiplayerApi, "luckLevel", () => Game1.player.luckLevel.Value, n => Game1.player.luckLevel.Value             = n);

            // Sync the exp
            SynchronizedList <int> expList = new SynchronizedList <int>(n => n.MakeSynchronized());

            multiplayerApi.Synchronize("expList", expList);
            foreach (int exp in Game1.player.experiencePoints)
            {
                expList.Add(exp);
            }
            GameEvents.UpdateTick += (sender, args) => {
                for (int i = 0; i < Game1.player.experiencePoints.Count; i++)
                {
                    int cur    = Game1.player.experiencePoints[i];
                    int synced = expList[i];

                    // Choose whichever is higher
                    if (cur < synced)
                    {
                        Game1.player.experiencePoints[i] = synced;
                    }
                    else if (synced < cur)
                    {
                        expList[i] = cur;
                    }
                }
            };
        }
        public void TestLock()
        {
            LockCounterFactory <SimpleReadWriteLocking> factory = new LockCounterFactory <SimpleReadWriteLocking>();
            ILockStrategy          lck  = factory.Create();
            SynchronizedList <int> list = new SynchronizedList <int>(lck);

            Assert.IsTrue(ReferenceEquals(lck, list.Lock));
            list.Add(42);
            Assert.AreEqual(1, factory.TotalWriterCount);
            Assert.AreEqual(0, factory.TotalReaderCount);

            list[0] = 51;
            Assert.AreEqual(2, factory.TotalWriterCount);

            list.Insert(1, 52);
            Assert.AreEqual(3, factory.TotalWriterCount);

            list.RemoveAt(1);
            Assert.AreEqual(4, factory.TotalWriterCount);

            list.Remove(-1);
            Assert.AreEqual(5, factory.TotalWriterCount);

            Assert.AreEqual(51, list[0]);
            Assert.AreEqual(1, factory.TotalReaderCount);

            foreach (int i in list)
            {
                GC.KeepAlive(i);
            }
            Assert.AreEqual(2, factory.TotalReaderCount);

            Assert.AreEqual(0, list.IndexOf(51));
            Assert.AreEqual(3, factory.TotalReaderCount);

            Assert.AreEqual(1, list.Count);
            Assert.AreEqual(4, factory.TotalReaderCount);
        }
Example #9
0
        public async Task TestSingleInstance_NotifyFirstInstance()
        {
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

            var applicationId = Guid.NewGuid();

            using var singleInstance = new SingleInstance(applicationId);
            Assert.True(singleInstance.StartApplication(), "Cannot start the instance");

            // Be sure the server is ready
            await Task.Delay(50);

            var events = new SynchronizedList <SingleInstanceEventArgs>();

            singleInstance.NewInstance += SingleInstance_NewInstance;

            Assert.True(singleInstance.NotifyFirstInstance(new[] { "a", "b", "c" }), "Cannot notify first instance 1");
            await Task.Delay(50);

            Assert.True(singleInstance.NotifyFirstInstance(new[] { "123" }), "Cannot notify first instance 2");

            while (!cts.Token.IsCancellationRequested && events.Count < 2)
            {
                await Task.Delay(50);
            }

            Assert.Equal(2, events.Count);
            var orderedEvents = events.OrderBy(args => args.Arguments.Length).ToList();

            Assert.Equal(new[] { "123" }, orderedEvents[0].Arguments);
            Assert.Equal(new[] { "a", "b", "c" }, orderedEvents[1].Arguments);

            void SingleInstance_NewInstance(object sender, SingleInstanceEventArgs e)
            {
                Assert.Equal(singleInstance, sender);
                events.Add(e);
            }
        }
Example #10
0
        private static void ExecuteConcurrentlyInternal(params Action[] actions)
        {
            if (actions.Length == 0)
            {
                return;
            }

            var errors          = new SynchronizedList <Exception>();
            var numberOfActions = actions.Length;
            var waitHandlers    = new AutoResetEvent[numberOfActions];

            for (var i = 0; i < numberOfActions; i++)
            {
                var action      = actions[i];
                var waitHandler = new AutoResetEvent(false);
                waitHandlers[i] = waitHandler;
                WaitCallback callback = state => {
                    try {
                        action();
                    } catch (Exception error) {
                        using (errors.EnterWriteScope()) {
                            errors.Add(error);
                        }
                    }
                    waitHandler.Set();
                };
                ThreadPool.QueueUserWorkItem(callback);
            }

            WaitHandle.WaitAll(waitHandlers);

            if (errors.Count > 0)
            {
                throw new AggregateException(errors);
            }
        }
Example #11
0
		public AuctionHouse()
		{
			auctions = new SynchronizedDictionary<uint, Auction>(10000);
			items = new SynchronizedList<uint>(10000);
		}
Example #12
0
		public StrategyInfo()
		{
            _strategies = new SynchronizedList<StrategyContainer>();
			_strategies.Added += s => s.ProcessStateChanged += StrategyProcessStateChanged;
			_strategies.Removed += s => s.ProcessStateChanged -= StrategyProcessStateChanged;
		}
 public SynchronizedList(SynchronizedList <T> queue)
 {
     m_List = new List <T>(queue.m_List);
     m_lock = new object();
 }
Example #14
0
 public static void OtherExample()
 {
     ICollection <string> collection = new SynchronizedList <string>(new List <string>());
 }
Example #15
0
        /// <summary>
        /// Listens for an incoming client connection and starts a new thread for client communication when a client connects.
        /// </summary>
        private void Listen()
        {
            SynchronizedList<Thread> threadList = new SynchronizedList<Thread>();

            listener.Start();
            listen = true;

            while (listen)
            {
                if (listener.Pending())
                {
                    TcpClient client = listener.AcceptTcpClient();

                    clientQueue.Enqueue(client);

                    Thread thread = new Thread(new ThreadStart(ServiceClient));
                    thread.IsBackground = true;
                    thread.Start();

                    threadList.Add(thread);
                }
                else
                {
                    Thread.Sleep(TimeSpan.Zero);
                }
            }

            listener.Stop();

            foreach (Thread thread in threadList)
            {
                thread.Join();
            }
        }
Example #16
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CodePanel"/>.
		/// </summary>
		public CodePanel()
		{
			InitializeComponent();

			_projectAssembly = new CSharpProjectAssembly("StudioStrategy");
			_projectAssembly.AssemblyReferences.AddMsCorLib();

			var language = new CSharpSyntaxLanguage();
			language.RegisterProjectAssembly(_projectAssembly);
			CodeEditor.Document.Language = language;

			_errorsSource = new ObservableCollection<CompileResultItem>();
			ErrorsGrid.ItemsSource = _errorsSource;

			var references = new SynchronizedList<CodeReference>();
			references.Added += r => _references.SafeAdd(r, r1 =>
			{
				IProjectAssemblyReference asmRef = null;

				try
				{
					asmRef = _projectAssembly.AssemblyReferences.AddFrom(r1.Location);
				}
				catch (Exception ex)
				{
					ex.LogError();
				}

				return asmRef;
			});
			references.Removed += r =>
			{
				var item = _projectAssembly
					.AssemblyReferences
					.FirstOrDefault(p =>
					{
						var assm = p.Assembly as IBinaryAssembly;

						if (assm == null)
							return false;

						return assm.Location == r.Location;
					});

				if (item != null)
					_projectAssembly.AssemblyReferences.Remove(item);
			};
			references.Cleared += () =>
			{
				_projectAssembly.AssemblyReferences.Clear();
				_projectAssembly.AssemblyReferences.AddMsCorLib();
			};

			References = references;
		}
 public ExecuteBackgroundCommandOnCollection(ILogger logDirector)
 {
     this.logDirector = logDirector;
     this.Commands = new SynchronizedList<IExecuteBackgroundCommand>();
 }
Example #18
0
 public AuctionHouse()
 {
     auctions = new SynchronizedDictionary <uint, Auction>(10000);
     items    = new SynchronizedList <uint>(10000);
 }
Example #19
0
 private GazeManager()
 {
     HeartbeatMillis = 3000; //default value
     gazeListeners = new SynchronizedList<IGazeListener>();
     calibrationResultListeners = new SynchronizedList<ICalibrationResultListener>();
     trackerStateListeners = new SynchronizedList<ITrackerStateListener>();
     connectionStateListeners = new SynchronizedList<IConnectionStateListener>();
     gazeQueue = new SingleFrameBlockingQueue<GazeData>();
 }
Example #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CodePanel"/>.
        /// </summary>
        public CodePanel()
        {
            InitializeComponent();

            _projectAssembly = new CSharpProjectAssembly("StudioStrategy");
            _projectAssembly.AssemblyReferences.AddMsCorLib();

            var language = new CSharpSyntaxLanguage();

            language.RegisterProjectAssembly(_projectAssembly);
            CodeEditor.Document.Language = language;

            _errorsSource          = new ObservableCollection <CompileResultItem>();
            ErrorsGrid.ItemsSource = _errorsSource;

            var references = new SynchronizedList <CodeReference>();

            references.Added += r => _references.SafeAdd(r, r1 =>
            {
                IProjectAssemblyReference asmRef = null;

                try
                {
                    asmRef = _projectAssembly.AssemblyReferences.AddFrom(r1.Location);
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }

                return(asmRef);
            });
            references.Removed += r =>
            {
                var item = _projectAssembly
                           .AssemblyReferences
                           .FirstOrDefault(p =>
                {
                    var assm = p.Assembly as IBinaryAssembly;

                    if (assm == null)
                    {
                        return(false);
                    }

                    return(assm.Location == r.Location);
                });

                if (item != null)
                {
                    _projectAssembly.AssemblyReferences.Remove(item);
                }
            };
            references.Cleared += () =>
            {
                _projectAssembly.AssemblyReferences.Clear();
                _projectAssembly.AssemblyReferences.AddMsCorLib();
            };

            References = references;
        }
 public LoggerContainer()
 {
     this.Loggers = new SynchronizedList<ILogger>();
 }
 private void ScheduleBackgroundProcess(SynchronizedList <IPsiSourceFile> toDelete, SynchronizedList <IPsiSourceFile> toProcess,
                                        ConcurrentDictionary <IPsiSourceFile, (long, Dictionary <IDeferredCache, object>)> calculatedData)
Example #23
0
 static Log()
 {
     Listeners = new SynchronizedList <LogListener>();
 }
Example #24
0
 public StrategyInfo()
 {
     _strategies          = new SynchronizedList <StrategyContainer>();
     _strategies.Added   += s => s.ProcessStateChanged += StrategyProcessStateChanged;
     _strategies.Removed += s => s.ProcessStateChanged -= StrategyProcessStateChanged;
 }
        //-----------------------------------------------------------------------

        /**
         * Returns a synchronized list backed by the given list.
         * <p>
         * You must manually synchronize on the returned buffer's iterator to
         * avoid non-deterministic behavior:
         *
         * <pre>
         * List list = ListUtils.synchronizedList(myList);
         * synchronized (list) {
         *     Iterator i = list.iterator();
         *     while (i.hasNext()) {
         *         process (i.next());
         *     }
         * }
         * </pre>
         *
         * This method uses the implementation in the decorators subpackage.
         *
         * @param list  the list to synchronize, must not be null
         * @return a synchronized list backed by the given list
         * @throws IllegalArgumentException  if the list is null
         */
        public static java.util.List <Object> synchronizedList(java.util.List <Object> list)
        {
            return(SynchronizedList.decorate(list));
        }
Example #26
0
            public override void Run()
            {
                try
                {
                    IDictionary <string, int?> values = new Dictionary <string, int?>();
                    IList <string>             allIDs = new SynchronizedList <string>();

                    StartingGun.Wait();
                    for (int iter = 0; iter < Iters; iter++)
                    {
                        // Add/update a document
                        Document doc = new Document();
                        // Threads must not update the same id at the
                        // same time:
                        if (ThreadRandom.NextDouble() <= AddChance)
                        {
                            string id    = string.Format(CultureInfo.InvariantCulture, "{0}_{1:X4}", ThreadID, ThreadRandom.Next(IdCount));
                            int    field = ThreadRandom.Next(int.MaxValue);
                            doc.Add(new StringField("id", id, Field.Store.YES));
                            doc.Add(new Int32Field("field", (int)field, Field.Store.YES));
                            w.UpdateDocument(new Term("id", id), doc);
                            Rt.Add(id, field);
                            if (!values.ContainsKey(id))//Key didn't exist before
                            {
                                allIDs.Add(id);
                            }
                            values[id] = field;
                        }

                        if (allIDs.Count > 0 && ThreadRandom.NextDouble() <= DeleteChance)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            w.DeleteDocuments(new Term("id", randomID));
                            Rt.Delete(randomID);
                            values[randomID] = Missing;
                        }

                        if (ThreadRandom.NextDouble() <= ReopenChance || Rt.Count > 10000)
                        {
                            //System.out.println("refresh @ " + rt.Size());
                            Mgr.MaybeRefresh();
                            if (VERBOSE)
                            {
                                IndexSearcher s = Mgr.Acquire();
                                try
                                {
                                    Console.WriteLine("TEST: reopen " + s);
                                }
                                finally
                                {
                                    Mgr.Release(s);
                                }
                                Console.WriteLine("TEST: " + values.Count + " values");
                            }
                        }

                        if (ThreadRandom.Next(10) == 7)
                        {
                            Assert.AreEqual(null, Rt.Get("foo"));
                        }

                        if (allIDs.Count > 0)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            int?   expected = values[randomID];
                            if (expected == Missing)
                            {
                                expected = null;
                            }
                            Assert.AreEqual(expected, Rt.Get(randomID), "id=" + randomID);
                        }
                    }
                }
                catch (Exception t)
                {
                    throw new Exception(t.Message, t);
                }
            }
 public RunCommandOnCollection(ILogger logDirector)
 {
     this.logDirector = logDirector;
     this.Commands = new SynchronizedList<IRunCommand>();
 }