/// <summary>
        /// Initializes a new instance of the <see cref="JobRunner"/> class.
        /// </summary>
        public JobRunner(IJobConfiguration configuration, Type jobType, JobLockProvider jobLockProvider, JobHistoryProvider jobHistoryProvider, IDependencyResolver dependencyResolver)
        {
            _id                = Guid.NewGuid().ToString("N").Substring(0, 10).ToLower();
            _isBusy            = new Synchronized <bool>();
            _lastResult        = new Synchronized <string>();
            _lastRunStartTime  = new Synchronized <DateTime>();
            _lastRunFinishTime = new Synchronized <DateTime>();
            _lastStatus        = new Synchronized <JobStatus>();
            _nextRunTime       = new Synchronized <DateTime>();
            _status            = new Synchronized <JobStatus>();
            _runLock           = new object();
            _name              = configuration.Name;
            _description       = configuration.Description;
            _group             = configuration.Group;
            _interval          = configuration.Interval;
            _isTimeOfDay       = configuration.IsTimeOfDay;
            _keepAlive         = configuration.KeepAlive;
            _arguments         = configuration.Arguments;

            _jobType            = jobType;
            _jobLockProvider    = jobLockProvider ?? new DefaultJobLockProvider();
            _dependencyResolver = dependencyResolver ?? new DefaultDependencyResolver();
            _jobHistoryProvider = jobHistoryProvider;

            _instance = null;
            _timer    = new Timer(OnTimerCallback);

            if (_jobHistoryProvider != null)
            {
                _jobHistoryProvider.RestoreHistory(this);
            }

            Trace.TraceInformation("Job {0} created on {1}.", Name, Environment.MachineName);
        }
Exemple #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JobRunner"/> class.
        /// </summary>
        public JobRunner(IJobConfiguration configuration, Type jobType, JobLockProvider jobLockProvider, JobHistoryProvider jobHistoryProvider, IDependencyResolver dependencyResolver)
        {
            _id = Guid.NewGuid().ToString("N").Substring(0, 10).ToLower();
            _isBusy = new Synchronized<bool>();
            _lastResult = new Synchronized<string>();
            _lastRunStartTime = new Synchronized<DateTime>();
            _lastRunFinishTime = new Synchronized<DateTime>();
            _lastStatus = new Synchronized<JobStatus>();
            _nextRunTime = new Synchronized<DateTime>();
            _status = new Synchronized<JobStatus>();
            _runLock = new object();
            _name = configuration.Name;
            _description = configuration.Description;
            _group = configuration.Group;
            _interval = configuration.Interval;
            _isTimeOfDay = configuration.IsTimeOfDay;
            _keepAlive = configuration.KeepAlive;
            _arguments = configuration.Arguments;

            _jobType = jobType;
            _jobLockProvider = jobLockProvider ?? new DefaultJobLockProvider();
            _dependencyResolver = dependencyResolver ?? new DefaultDependencyResolver();
            _jobHistoryProvider = jobHistoryProvider;

            _instance = null;
            _timer = new Timer(OnTimerCallback);

            if (_jobHistoryProvider != null)
                _jobHistoryProvider.RestoreHistory(this);

            Trace.TraceInformation("Job {0} created on {1}.", Name, Environment.MachineName);
        }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:LFNet.Common.Scheduler.Job" /> class.
 /// </summary>
 public Job(IJobConfiguration configuration, Type jobType, JobLockProvider jobLockProvider, JobHistoryProvider jobHistoryProvider)
 {
     this._id                 = Guid.NewGuid().ToString("N").Substring(0, 10).ToLower();
     this._isBusy             = new Synchronized <bool>();
     this._lastResult         = new Synchronized <string>();
     this._lastRunStartTime   = new Synchronized <DateTime>();
     this._lastRunFinishTime  = new Synchronized <DateTime>();
     this._lastStatus         = new Synchronized <JobStatus>();
     this._nextRunTime        = new Synchronized <DateTime>();
     this._status             = new Synchronized <JobStatus>();
     this._runLock            = new object();
     this._name               = configuration.Name;
     this._description        = configuration.Description;
     this._group              = configuration.Group;
     this._interval           = configuration.Interval;
     this._isTimeOfDay        = configuration.IsTimeOfDay;
     this._keepAlive          = configuration.KeepAlive;
     this._arguments          = configuration.Arguments;
     this._jobType            = jobType;
     this._jobLockProvider    = jobLockProvider ?? new DefaultJobLockProvider();
     this._jobHistoryProvider = jobHistoryProvider;
     this._instance           = null;
     this._timer              = new Timer(new TimerCallback(this.OnTimerCallback));
     if (this._jobHistoryProvider != null)
     {
         this._jobHistoryProvider.RestoreHistory(this);
     }
 }
        public void Constructor_Mutex_And_Value_Success()
        {
            // arrange
            const string value = "bar";

            // act
            var synchronized = new Synchronized <string>(new object(), value);

            // assert
            Assert.Equal(value, synchronized.Read());
        }
        public void ReadDirty_Success()
        {
            // arrange
            const string value        = "foo";
            var          synchronized = new Synchronized <string>(value);

            // act
            var result = synchronized.ReadDirty();

            // assert
            Assert.Equal(value, result);
        }
Exemple #6
0
            volatile Synchronized <object>?obj; // volatile is sufficient for this usage

            public void Foo()
            {
                new Thread(() =>
                {
                    obj?.WithLock(o =>
                    {
                        Console.WriteLine(o.ToString());
                    });
                }).Start();

                obj = Synchronized.Create(new object());
            }
        public void Write_Returns_True_If_Value_Is_Same()
        {
            // arrange
            const string value        = "bar";
            var          synchronized = new Synchronized <string>("foo");

            // act
            var result = synchronized.Write(value);

            // assert
            Assert.True(result);
            Assert.Equal(value, synchronized.Read());
        }
Exemple #8
0
 /// <summary>
 /// reset the settings to the state they have on disk, useful for process that does not write settings but needs current version
 /// </summary>
 /// <param name="since"></param>
 /// <returns></returns>
 public bool SynchronizeSettings(DateTime?since)
 {
     try
     {
         if (since.HasValue)
         {
             if (File.GetLastWriteTime(_settingsFile) < since.Value)
             {
                 return(false);
             }
         }
         _settings = LoadSettingsFile();
         Synchronized?.Invoke(this, EventArgs.Empty);
         return(true);
     }
     catch (System.Exception ex)
     {
         Logger.Error(ex, $"the settings file '{_settingsFile}' has become corrupted; writing new file from settings we have in memory");
         SaveSettings();
         return(false);
     }
 }
Exemple #9
0
 public void TriggerSynchronized()
 {
     Synchronized?.Invoke(this, EventArgs.Empty);
 }
Exemple #10
0
        public static void EntitiesContextInitialization <T>() where T : EntitiesContext
        {
            if (_contexts.Value.FirstOrDefault(c => c.Name == (typeof(T).Name)).IsNull())
            {
                string sessionid = MVCEngine.Tools.Session.Session.CreateUserSession(typeof(T).Name);
                Task   task      = new Task(() =>
                {
                    Dictionary <MVCEngine.Model.Internal.Descriptions.DynamicProperties, string[]> dynamicList =
                        new Dictionary <MVCEngine.Model.Internal.Descriptions.DynamicProperties, string[]>();
                    Context ctx = new Context()
                    {
                        Name    = typeof(T).Name,
                        Entites = new List <EntityClass>()
                    };
                    _contexts.Value.Add(ctx);
                    _entitiesCollection.Value.Add(ctx.Name, new Dictionary <string, Func <object, object> >());

                    typeof(T).GetFields().Where(f => f.FieldType.Name == "EntitiesCollection`1" && f.IsPublic).
                    ToList().ForEach((f) =>
                    {
                        List <string> realTimeValidator = new List <string>();
                        PropertyInfo ctxInfo            = f.FieldType.GetProperty("Context");
                        Type entityType = f.FieldType.GetGenericArguments().First <Type>();
                        Debug.Assert(typeof(Entity).IsAssignableFrom(entityType), "Entity[" + entityType.FullName + "] it cann't be recognise as valid entity.");
                        if (typeof(Entity).IsAssignableFrom(entityType))
                        {
                            if (!_entites.Value.ContainsKey(entityType.FullName))
                            {
                                EntityClass entityClass = new EntityClass();
                                Debug.Assert(!ctx.Entites.Exists((t) => { return(t.Name == entityType.Name); }), "Entity[" + entityType.Name + "] is defined twice.");
                                if (!ctx.Entites.Exists((t) => { return(t.Name == entityType.Name); }))
                                {
                                    entityClass.Name       = entityType.Name;
                                    entityClass.EntityType = entityType;
                                    entityClass.Attributes.AddRange(Attribute.GetCustomAttributes(entityType));

                                    _entitiesCollection.Value[ctx.Name].Add(entityType.Name, LambdaTools.FieldGetter(typeof(T), f));

                                    var propertyquery = entityType.GetProperties().Where(p => p.CanRead && p.GetGetMethod().IsVirtual);
                                    propertyquery.ToList().ForEach((p) =>
                                    {
                                        EntityProperty property = new EntityProperty()
                                        {
                                            Name         = p.Name,
                                            PropertyType = p.PropertyType,
                                            PropertyInfo = p,
                                            Setter       = p.CanWrite ? LambdaTools.PropertySetter(entityType, p) : null,
                                            Getter       = LambdaTools.PropertyGetter(entityType, p)
                                        };
                                        property.Attibutes.AddRange(Attribute.GetCustomAttributes(p));
                                        entityClass.Properties.Add(property);

                                        if (typeof(Entity).IsAssignableFrom(p.PropertyType))
                                        {
                                            property.ReletedEntity = new ReletedEntity()
                                            {
                                                Related           = Releted.Entity,
                                                RelatedEntityName = p.PropertyType.Name
                                            };
                                        }
                                        else if (p.PropertyType.Name == "EntitiesCollection`1")
                                        {
                                            property.ReletedEntity = new ReletedEntity()
                                            {
                                                Related           = Releted.List,
                                                RelatedEntityName = p.PropertyType.GetGenericArguments().First <Type>().Name
                                            };
                                        }
                                        Attribute.GetCustomAttributes(p).ToList().ForEach((a) =>
                                        {
                                            Relation relation           = null;
                                            Discriminator discriminator = null;
                                            PropertyValidator validator = null;
                                            DefaultValue defaultValue   = null;
                                            Synchronized synchronized   = null;
                                            Formatter formatter         = null;
                                            NotIntercept notIntercept   = null;
                                            Intercept intercept         = null;
                                            attribute.DynamicProperties dynamicProperties = null;
                                            if (a.IsTypeOf <PrimaryKey>())
                                            {
                                                Debug.Assert(entityClass.Properties.FirstOrDefault(primary => primary.PrimaryKey).IsNull(), "Entity[" + entityType.Name + "] at least two primary key property defined");
                                                property.PrimaryKey            = true;
                                                entityClass.PrimaryKeyProperty = property;
                                                entityClass.PrimaryKey         = property.Getter;
                                            }
                                            else if ((relation = a.CastToType <Relation>()).IsNotNull())
                                            {
                                                EntitiesRelation r = ctx.Relations.FirstOrDefault(re => re.Name == relation.RelationName);
                                                Debug.Assert(r.IsNull(), "Relation[" + relation.RelationName + "] is declared at least twice");
                                                if (property.ReletedEntity.IsNotNull())
                                                {
                                                    EntitiesRelation entityrelation = new EntitiesRelation()
                                                    {
                                                        Name   = relation.RelationName,
                                                        Parent = new EntityRelated()
                                                        {
                                                            EntityName = relation.ParentEntity,
                                                            Key        = relation.ParentProperty
                                                        },
                                                        Child = new EntityRelated()
                                                        {
                                                            EntityName = relation.ChildEntity,
                                                            Key        = relation.ChildProperty
                                                        },
                                                        OnDelete = relation.OnDelete,
                                                        OnAccept = relation.OnAccept,
                                                        OnFreeze = relation.OnFreeze
                                                    };
                                                    ctx.Relations.Add(entityrelation);
                                                    property.ReletedEntity.Relation = entityrelation;
                                                }
                                            }
                                            else if ((synchronized = a.CastToType <Synchronized>()).IsNotNull())
                                            {
                                                if (property.ReletedEntity.IsNotNull())
                                                {
                                                    property.ReletedEntity.Synchronized = true;
                                                }
                                            }
                                            else if ((discriminator = a.CastToType <Discriminator>()).IsNotNull())
                                            {
                                                if (property.ReletedEntity.IsNotNull())
                                                {
                                                    property.ReletedEntity.Discriminators.Add(discriminator);
                                                }
                                            }
                                            else if ((validator = a.CastToType <PropertyValidator>()).IsNotNull())
                                            {
                                                property.Validators.Add(validator);
                                            }
                                            else if ((defaultValue = a.CastToType <DefaultValue>()).IsNotNull())
                                            {
                                                property.DefaultValue = defaultValue;
                                            }
                                            else if ((dynamicProperties = a.CastToType <attribute.DynamicProperties>()).IsNotNull())
                                            {
                                                if (property.ReletedEntity.IsNotNull() && property.ReletedEntity.Related == Releted.List)
                                                {
                                                    entityClass.DynamicProperties = new Internal.Descriptions.DynamicProperties()
                                                    {
                                                        CodeProperty = dynamicProperties.CodeProperty,
                                                        Property     = property,
                                                    };
                                                    dynamicList.Add(entityClass.DynamicProperties, dynamicProperties.ValueProperties);
                                                }
                                            }
                                            else if ((formatter = a.CastToType <Formatter>()).IsNotNull())
                                            {
                                                property.AddFormatter(formatter);
                                            }
                                            else if ((notIntercept = a.CastToType <NotIntercept>()).IsNotNull())
                                            {
                                                if (notIntercept.InterceptorId.IsNullOrEmpty())
                                                {
                                                    property.RemoveGetInterceptor(string.Empty);
                                                    property.RemoveSetInterceptor(string.Empty);
                                                }
                                                else
                                                {
                                                    if (notIntercept.Method == Method.Get)
                                                    {
                                                        property.RemoveGetInterceptor(notIntercept.InterceptorId);
                                                    }
                                                    else
                                                    {
                                                        property.RemoveSetInterceptor(notIntercept.InterceptorId);
                                                    }
                                                }
                                            }
                                            else if ((intercept = a.CastToType <Intercept>()).IsNotNull() && intercept.Method.IsNotNull())
                                            {
                                                if (intercept.Method.Contains(Method.Get))
                                                {
                                                    property.AddGetInterceptor(intercept.InterceptorId);
                                                }

                                                if (intercept.Method.Contains(Method.Set))
                                                {
                                                    property.AddSetInterceptor(intercept.InterceptorId);
                                                }
                                            }
                                        });
                                    });
                                    Attribute.GetCustomAttributes(entityType).ToList().ForEach((a) =>
                                    {
                                        EntityValidator validator = null;
                                        if ((validator = a.CastToType <EntityValidator>()).IsNotNull())
                                        {
                                            entityClass.Validators.Add(validator);
                                        }
                                    });
                                    ctx.Entites.Add(entityClass);
                                }
                                _entites.Value.Add(entityType.FullName, entityClass);
                            }
                            else
                            {
                                ctx.Entites.Add(_entites.Value[entityType.FullName]);
                            }
                        }
                    });
                    ctx.Relations.ForEach((r) =>
                    {
                        EntityClass entity = ctx.Entites.FirstOrDefault(e => e.Name == r.Parent.EntityName);
                        Debug.Assert(entity.IsNotNull(), "Relation[" + r.Name + "] parent entity not found");
                        r.Parent.Entity         = entity;
                        EntityProperty property = entity.Properties.FirstOrDefault(p => p.Name == r.Parent.Key);
                        Debug.Assert(property.IsNotNull(), "Entity[" + entity.Name + "] property[" + r.Parent.Key + "] not defined");
                        r.Parent.Type  = property.PropertyType;
                        r.Parent.Value = property.Getter;

                        EntityClass childEntity = ctx.Entites.FirstOrDefault(e => e.Name == r.Child.EntityName);
                        Debug.Assert(childEntity.IsNotNull(), "Relation[" + r.Name + "] child entity not found");
                        r.Child.Entity = childEntity;
                        EntityProperty childProperty = childEntity.Properties.FirstOrDefault(p => p.Name == r.Child.Key);
                        Debug.Assert(childProperty.IsNotNull(), "Entity[" + childEntity.Name + "] property[" + r.Child.Key + "] not defined");
                        r.Child.Type  = childProperty.PropertyType;
                        r.Child.Value = childProperty.Getter;
                    });

                    var reletedquery = ctx.Entites.Where(e => e.Properties.Count(p => p.ReletedEntity.IsNotNull()) > 0).
                                       SelectMany(e => e.Properties.Where(p => p.ReletedEntity.IsNotNull()), (e, p) => new { Entity = e, Property = p });

                    reletedquery.ToList().ForEach((ep) =>
                    {
                        EntityClass entityClass = ctx.Entites.FirstOrDefault(e => e.Name == ep.Property.ReletedEntity.RelatedEntityName);
                        Debug.Assert(entityClass.IsNotNull(), "Entity[" + ep.Property.ReletedEntity.RelatedEntityName + "] dosen't have collection");
                        ep.Property.ReletedEntity.RelatedEntity = entityClass;
                        if (ep.Property.ReletedEntity.Relation.IsNull())
                        {
                            if (!ep.Property.ReletedEntity.RelationName.IsNullOrEmpty())
                            {
                                EntitiesRelation relation = ctx.Relations.FirstOrDefault(r => r.Name == ep.Property.ReletedEntity.RelationName);
                                Debug.Assert(relation.IsNotNull(), "Relation[" + ep.Property.ReletedEntity.RelationName + "] not defined");
                                ep.Property.ReletedEntity.Relation = relation;
                            }
                            else
                            {
                                List <EntitiesRelation> relations = null;
                                if (ep.Property.ReletedEntity.Related == Releted.Entity)
                                {
                                    relations = ctx.Relations.Where(r => r.Parent.EntityName == ep.Property.ReletedEntity.RelatedEntityName && r.Child.EntityName == ep.Entity.Name).ToList();
                                }
                                else
                                {
                                    relations = ctx.Relations.Where(r => r.Parent.EntityName == ep.Entity.Name && r.Child.EntityName == ep.Property.ReletedEntity.RelatedEntityName).ToList();
                                }

                                Debug.Assert(relations.Count() < 2, "Relation[" + ep.Property.ReletedEntity.RelatedEntityName + "-" + ep.Entity.Name + "] more then one");
                                if (relations.Count() == 1)
                                {
                                    ep.Property.ReletedEntity.Relation = relations[0];
                                }
                            }
                        }
                        if (ep.Property.ReletedEntity.Synchronized)
                        {
                            ep.Property.ReletedEntity.RelatedEntity.Synchronized(ep.Entity.Name, ep.Property.Name);
                        }
                        if (ep.Property.ReletedEntity.Related == Releted.List)
                        {
                            ep.Property.AddGetInterceptor(CollectionInterceptorDispatcher.GetId(ep.Property.ReletedEntity.Relation.Child.Entity.EntityType));
                        }
                        else
                        {
                            ep.Property.AddGetInterceptor(EntityInterceptorDispatcher.GetId(ep.Property.ReletedEntity.RelatedEntityName));
                        }
                    });

                    foreach (MVCEngine.Model.Internal.Descriptions.DynamicProperties dynamicProperty in dynamicList.Keys)
                    {
                        foreach (string p in dynamicList[dynamicProperty])
                        {
                            EntityProperty property = dynamicProperty.Property.ReletedEntity.RelatedEntity.Properties.FirstOrDefault(pr => pr.Name == p);
                            if (property.IsNotNull())
                            {
                                dynamicProperty.ValuesProperties.Add(property.PropertyType, property.Name);
                            }
                        }
                    }
                });

                task.ContinueWith((antecedent) =>
                {
                    MVCEngine.Tools.Session.Session.ReleaseSession(sessionid);
                });

                task.ContinueWith((antecedent) =>
                {
                    if (_contexts.IsValueCreated)
                    {
                        _contexts.Value.Clear();
                    }
                    //ToDo log exception into log file
                }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);

                MVCEngine.Tools.Session.Session.SetSessionData(sessionid, "InitializeTask", task);

                task.Start();
            }
        }
Exemple #11
0
        private void Dining()
        {
            for (var method = (Method)0; method < Method.Count; ++method)
            {
                for (var nt = 2; nt <= 32; ++nt)
                {
                    ForceGC();
                    var table      = new List <IBareLock>();
                    var lockOrders = new Dictionary <IBareLock, int>();
                    for (var i = 0; i < nt; ++i)
                    {
                        table.Add(Synchronized.Create(new object()));
                        lockOrders[table[i]] = i;
                    }

                    var diners = new List <Philosopher>();
                    for (var i = 0; i < nt; ++i)
                    {
                        int j = i;
                        int k = j < nt - 1 ? j + 1 : 0;
                        Action <IReadOnlyList <IBareLock>, Action> lockToEat = null;
                        switch (method)
                        {
                        case Method.Ordered:
                            lockToEat = (locks, eat) =>
                            {
                                locks = locks.OrderBy(x => lockOrders[x]).ToList();
                                foreach (var l in locks)
                                {
                                    l.BarelyLock();
                                }
                                eat();
                                foreach (var l in locks)
                                {
                                    l.BarelyUnlock();
                                }
                            };
                            break;

                        case Method.SmartAndPolite:
                            lockToEat = (locks, eat) =>
                            {
                                using (MultiSync.All(locks))
                                {
                                    eat();
                                }
                            };
                            break;
                        }
                        diners.Add(new Philosopher(new[] { table[j], table[k] }, lockToEat));
                    }
                    var threads   = new List <Thread>();
                    var stopwatch = new Stopwatch();
                    for (var i = 0; i < nt; ++i)
                    {
                        threads.Add(new Thread(diners[i].Dine));
                    }
                    stopwatch.Start();
                    for (var i = 0; i < nt; ++i)
                    {
                        threads[i].Start();
                    }
                    foreach (var t in threads)
                    {
                        t.Join();
                    }
                    stopwatch.Stop();
                    Console.WriteLine($"{method},{nt},{stopwatch.Elapsed.TotalSeconds}");
                }
            }
        }
Exemple #12
0
        private async Task TestSynchronizeMultipleAsync(int repeat, bool output)
        {
            var watch = new Stopwatch();

            var x1   = new X();
            var x2   = new X();
            var sqrt = (int)Math.Sqrt(1);

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                lock (x1)
                {
                    lock (x2)
                    {
                        x1.Value += sqrt;
                        x2.Value += sqrt;
                    }
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"lock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            var syncMonitor1 = Synchronized.Create(x1);
            var syncMonitor2 = Synchronized.Create(x2);

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var v1 = syncMonitor1.Lock())
                    using (var v2 = syncMonitor2.Lock())
                    {
                        v1.Value.Value += sqrt;
                        v2.Value.Value += sqrt;
                    }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"Synchronized.Lock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var guard = MultiSync.All(new[] { syncMonitor1, syncMonitor2 }))
                {
                    guard.Value[0].Value += sqrt;
                    guard.Value[1].Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"MultiSync.All Monitor,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            var syncMonitors = new[] { syncMonitor1, syncMonitor2 };

            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var guard = MultiSync.All(syncMonitors))
                {
                    guard.Value[0].Value += sqrt;
                    guard.Value[1].Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"MultiSync.All Monitor reusing array,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            var semaphore1 = new SemaphoreSlim(1);
            var semaphore2 = new SemaphoreSlim(1);

            for (int i = 0; i < repeat; ++i)
            {
                await semaphore1.WaitAsync().ConfigureAwait(false);

                await semaphore2.WaitAsync().ConfigureAwait(false);

                x1.Value += sqrt;
                x2.Value += sqrt;
                semaphore2.Release();
                semaphore1.Release();
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"SemaphoreSlim.WaitAsync,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            var syncSemaphore1 = AsyncSynchronized.Create(x1);
            var syncSemaphore2 = AsyncSynchronized.Create(x2);

            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var guard = await MultiSync.AllAsync(new[] { syncSemaphore1, syncSemaphore2 }).ConfigureAwait(false))
                {
                    guard.Value[0].Value += sqrt;
                    guard.Value[1].Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"MultiSync.AllAsync SemaphoreSlim,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }
        }
Exemple #13
0
        public async Task TestSynchronizedAsync(int repeat, bool output)
        {
            var watch = new Stopwatch();

            var x    = new X();
            var sqrt = (int)Math.Sqrt(1);

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                lock (x)
                {
                    x.Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"lock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            var syncMonitor = Synchronized.Create(x);

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                syncMonitor.WithLock((v) => v.Value += sqrt);
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"Synchronized.WithLock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var guard = syncMonitor.Lock())
                {
                    guard.Value.Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"Synchronized.Lock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            var semaphore = new SemaphoreSlim(1);

            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                semaphore.Wait();
                x.Value += sqrt;
                semaphore.Release();
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"SemaphoreSlim.Wait,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            var syncSemaphore = AsyncSynchronized.Create(x);

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                syncSemaphore.WithLock((v) => v.Value += sqrt);
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"AsyncSynchronized.WithLock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var guard = syncSemaphore.Lock())
                {
                    guard.Value.Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"AsyncSynchronized.Lock,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                await semaphore.WaitAsync().ConfigureAwait(false);

                x.Value += sqrt;
                semaphore.Release();
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"SemaphoreSlim.WaitAsync,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                await syncSemaphore.WithLockAsync((v) => v.Value += sqrt).ConfigureAwait(false);
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"AsyncSynchronized.WithLockAsync,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }

            ForceGC();
            watch.Restart();
            for (int i = 0; i < repeat; ++i)
            {
                using (var guard = await syncSemaphore.LockAsync().ConfigureAwait(false))
                {
                    guard.Value.Value += sqrt;
                }
            }
            watch.Stop();
            if (output)
            {
                Console.WriteLine($"AsyncSynchronized.LockAsync,{((double)watch.ElapsedTicks * 100 / repeat)}");
            }
        }
Exemple #14
0
        private bool SynchronizeStatus(Synchronized s)
        {
            SyncStatus status = s as SyncStatus;
            if (status == null || status.IsMine()) return false;

            if(status.Status == NetworkStatus.Dead)
            {
                Debug.Log("[dead] id=" + status.Id);
                PlayerController controller = PlayerController.Get(status.Id);
                if (controller == null) return false;
                controller.Alive = false;
                return true;
            }
            if(status.Status == NetworkStatus.Born)
            {
                Debug.Log("[born] id=" + status.Id);
                PlayerController controller = PlayerController.Get(status.Id);
                if (controller == null) return false;
                controller.Alive = true;
                return true;
            }
            return true;
        }
Exemple #15
0
        private bool SynchronizePlayer(Synchronized s)
        {
            SyncPlayer player = s as SyncPlayer;
            if (player == null || player.IsMine()) return false;

            PlayerController controller = PlayerController.Get(player.Id);
            if(controller == null)
            {
                // プレイヤーの新規作成
                GameObject o = Instantiate(ConstantEnviroment.Instance.PrefabPlayer) as GameObject;
                controller = o.GetComponent<PlayerController>();
                controller.Register(player);
                o.name = "Player-" + player.Group + "." + player.Id;
                Debug.Log("[created] id=" + player.Id);
            }
            controller.Recieve(player);
            return true;
        }
Exemple #16
0
        private bool SynchronizeBall(Synchronized s)
        {
            SyncBall ball = s as SyncBall;
            if (ball == null) return false;
            if(ball.IsMine())
            {
                return false;
            }
            PlayerController controller = PlayerController.Get(ball.Id);
            if (controller == null) return false;
            if (!controller.Alive) return false;

            GameObject o = Instantiate(ConstantEnviroment.Instance.PrefabInkBall) as GameObject;
            o.GetComponent<InkBallController>().Initialize(ball);
            return true;
        }