Exemplo n.º 1
0
        public ScopeManager()
        {
            string key = DomainItem.CheckName(AppScopeNames.Legacy);

            _dict.Locked(dict => dict.Add(key, new DomainItem()));
            _defaultDomain = AppScopeNames.Legacy;
        }
Exemplo n.º 2
0
        private void ReceiveTradeValuationResult(HandlerResponse pvRes)
        {
            var requestId = new Guid(pvRes.RequestId);

            // ignore requests if we are not running
            if (GetState() != BasicServerState.Running)
            {
                return;
            }

            _outstandingRequests.Locked(requests =>
            {
                InternalTradeRevalRequest request;
                if (requests.TryGetValue(requestId, out request))
                {
                    // exists
                    request.LatestResult = pvRes;
                }
                else
                {
                    // not found
                    request             = new InternalTradeRevalRequest(requestId, pvRes);
                    requests[requestId] = request;
                }
            });

            // dispatch worker request
            _workerEventQueue.Dispatch(null);
        }
Exemplo n.º 3
0
 /// <summary>
 /// The attach method.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="part"></param>
 public void Attach(string name, IServerPart part)
 {
     if (part != null)
     {
         _attachedParts.Locked((attachedParts) => attachedParts[name] = part);
         //Logger.LogDebug("ServerPart '{0}' attached.", name);
         OnAttached(name, part);
     }
     //else
     //    Logger.LogDebug("ServerPart '{0}' not attached.", name);
 }
Exemplo n.º 4
0
 public void Enqueue(IAsyncResult asyncOperation)
 {
     _queue.Locked(queue =>
     {
         queue.Enqueue(asyncOperation);
         while (queue.Count > _maxQueueLength)
         {
             IAsyncResult ar = queue.Dequeue();
             ((AsyncResultNoResult)ar).EndInvoke();
         }
     });
 }
Exemplo n.º 5
0
        public ProviderRuleSet ExportRules()
        {
            var list = new List <QRMarketDataMap>();

            _rules.Locked(rules =>
            {
                foreach (MapRule rule in rules)
                {
                    list.Add(new QRMarketDataMap
                    {
                        dictType       = rule.DictType,
                        disabled       = rule.Disabled,
                        priority       = rule.Priority,
                        requestType    = rule.RequestType,
                        sourceProvider = rule.SourceProvider,
                        targetProvider = rule.TargetProvider,
                        sourcePattern  = rule.SearchValue,
                        outputValue    = rule.OutputValue
                    });
                }
            });
            return(new ProviderRuleSet {
                provider = _provider, rules = list.ToArray()
            });
        }
Exemplo n.º 6
0
        protected override void  OnStatsTimeoutReportDeltas()
        {
            base.OnStatsTimeoutReportDeltas();
            int  pendingInserts = 0;
            int  pendingDeletes = 0;
            long completedOps   = 0;
            long dbExceptions   = 0;

            _state.Locked(state =>
            {
                pendingInserts = state.InsertQueue.Count;
                pendingDeletes = state.DeleteQueue.Count;
                dbExceptions   = state.ExceptionCount;
                completedOps   = state.CompletedCount;
            });
            Logger.LogDebug("Enqueued operations : {0}", _inboundCallQueue.Length);
            Logger.LogDebug("Pending  insert ops : {0}", pendingInserts);
            Logger.LogDebug("Pending  delete ops : {0}", pendingDeletes);
            Logger.LogDebug("Completed operations: {0}", completedOps);
            Logger.LogDebug("Database exceptions : {0}", dbExceptions);
        }
Exemplo n.º 7
0
        private void ReceivePortfolioValuationResult(ServerRequestStatus pvRes)
        {
            Guid requestId = new Guid(pvRes.RequestId);

            _OutstandingRequests.Locked((requests) =>
            {
                InternalRequest request;
                if (requests.TryGetValue(requestId, out request))
                {
                    // exists
                    request.LatestResult = pvRes;
                }
                else
                {
                    // not found
                    request             = new InternalRequest(requestId, pvRes);
                    requests[requestId] = request;
                }
            });

            // dispatch worker request
            EnqueueWorkerRequest();
        }
Exemplo n.º 8
0
        public void ProcessItems()
        {
            int count = Interlocked.Decrement(ref _queuedCalls);

            // exit if there are more callbacks following us
            if (count % 10000 == 0)
            {
                _loggerRef.Target.LogDebug("ProcessItems: Queued calls remaining: {0}", count);
            }
            if (count != 0)
            {
                return;
            }
            // start updating the display
            treeNavigation.BeginUpdate();
            ICoreItem item = null;

            _queuedItems.Locked(queue =>
            {
                if (queue.Count > 0)
                {
                    item = queue.Dequeue();
                }
            });
            while (item != null)
            {
                // add item to navigation tree
                TreeNode[] rootNodes = null;
                switch (item.ItemKind)
                {
                case ItemKind.Object:
                    rootNodes = treeNavigation.Nodes.Find("Objects", false);
                    break;

                case ItemKind.Debug:
                    rootNodes = treeNavigation.Nodes.Find("Debug", false);
                    break;
                    //case ItemKind.Signal:
                    //    rootNodes = treeNavigation.Nodes.Find("Signals", false);
                    //    break;
                }
                if (rootNodes != null)
                {
                    TreeNode parentNode    = rootNodes[0];
                    TreeNode thisNode      = null;
                    string[] itemNameParts = item.Name.Split('.');
                    foreach (string itemNamePart in itemNameParts)
                    {
                        TreeNode[] nodes = parentNode.Nodes.Find(itemNamePart, false);
                        if (nodes.Length == 0)
                        {
                            // not found - add node at this level
                            thisNode      = parentNode.Nodes.Insert(FindIndex(parentNode.Nodes, itemNamePart), itemNamePart);
                            thisNode.Name = itemNamePart;
                        }
                        else
                        {
                            // found
                            thisNode = nodes[0];
                        }
                        // next
                        parentNode = thisNode;
                    }
                    if (thisNode != null)
                    {
                        thisNode.Tag = item;
                    }
                }
                if (item.Name == _navDetailSubject)
                {
                    DisplayItemInNavDetail(item);
                }
                item = null;
                _queuedItems.Locked(queue =>
                {
                    if (queue.Count > 0)
                    {
                        item = queue.Dequeue();
                    }
                });
            }
            treeNavigation.EndUpdate();
        }
Exemplo n.º 9
0
 internal void Enqueue(DispatcherItem item)
 {
     _Queue.Locked((queue) => queue.Enqueue(item));
     ThreadPool.QueueUserWorkItem(AsyncProcessNode, null);
 }
Exemplo n.º 10
0
        private void ProcessRequests(object notUsed)
        {
            try
            {
                // process rules and run handlers as required
                BasicServerState state = this.GetState();
                if (state != BasicServerState.Running)
                {
                    return;
                }

                // subscription is ready and callback flood has stopped
                List <InternalRequest> existingRequests  = new List <InternalRequest>();
                List <InternalRequest> enqueuedRequests  = new List <InternalRequest>();
                List <InternalRequest> cancelledRequests = new List <InternalRequest>();
                var requestItems      = _AssignedRequestsCache.Items;
                var cancellationItems = _CancellationsCache.Items;
                var responseItems     = _WorkerResponseCache.Items;
                _InternalRequests.Locked((internalRequests) =>
                {
                    // - process responses
                    foreach (ICoreItem item in responseItems)
                    {
                        try
                        {
                            WorkerResponse response = (WorkerResponse)item.Data;
                            Guid requestId          = Guid.Parse(response.RequestId);
                            InternalRequest internalRequest;
                            if (!internalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Status      = response.Status;
                            internalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process requests
                    foreach (ICoreItem item in requestItems)
                    {
                        try
                        {
                            AssignedWorkflowRequest request = (AssignedWorkflowRequest)item.Data;
                            Guid requestId = Guid.Parse(request.RequestId);
                            InternalRequest internalRequest;
                            if (!internalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.ExternalRequest = request;
                            internalRequests[requestId]     = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process cancellations
                    foreach (ICoreItem item in cancellationItems)
                    {
                        try
                        {
                            CancellationRequest cancellation = (CancellationRequest)item.Data;
                            Guid requestId = Guid.Parse(cancellation.RequestId);
                            InternalRequest internalRequest;
                            if (!internalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Cancellation = cancellation;
                            internalRequests[requestId]  = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }

                    // determine requests to be launched or cancelled
                    foreach (InternalRequest internalRequest in internalRequests.Values)
                    {
                        if ((internalRequest.ExternalRequest != null) &&
                            ((internalRequest.Status == RequestStatusEnum.Undefined) || (internalRequest.Status == RequestStatusEnum.Enqueued)))
                        {
                            // find requests to launch
                            if (internalRequest.Cancellation == null)
                            {
                                if (internalRequest.Status != RequestStatusEnum.Enqueued)
                                {
                                    // new request
                                    internalRequest.Status = RequestStatusEnum.Enqueued;
                                    enqueuedRequests.Add(internalRequest);
                                }
                                existingRequests.Add(internalRequest);
                            }
                            else
                            {
                                // cancelled
                                internalRequest.Status = RequestStatusEnum.Cancelled;
                                cancelledRequests.Add(internalRequest);
                            }
                        }
                    }
                });

                // publish status for cancelled and enqueued requests
                foreach (InternalRequest request in cancelledRequests)
                {
                    PublishWorkerResponse(_IntClient.Target, request, HostInstance);
                }

                // now find handlers to launch
                foreach (InternalRequest request in enqueuedRequests)
                {
                    // publish enqueued status
                    PublishWorkerResponse(_IntClient.Target, request, HostInstance);
                }
                foreach (InternalRequest request in existingRequests)
                {
                    // launch if handler available
                    int count = Interlocked.Decrement(ref _HandlersAvailable);
                    if (count >= 0)
                    {
                        Interlocked.Increment(ref _AvailabilityChangeCount);
                        Interlocked.Increment(ref _HandlersExecuting);
                        // publish launched status
                        request.Status = RequestStatusEnum.Launched;
                        PublishWorkerResponse(_IntClient.Target, request, HostInstance);
                        // launch
                        ThreadPool.QueueUserWorkItem(Launch, new LaunchPackage(_IntClient, request));
                    }
                    else
                    {
                        Interlocked.Increment(ref _HandlersAvailable);
                    }
                }

                // publish availability (throttled)
                int changeCount = Interlocked.Exchange(ref _AvailabilityChangeCount, 0);
                if ((changeCount > 0) || ((DateTimeOffset.Now - _AvailabilityLastPublished) > TimeSpan.FromSeconds(5)))
                {
                    _IntClient.Target.SaveObject <WorkerAvailability>(new WorkerAvailability()
                    {
                        WorkerHostComputer = Environment.MachineName,
                        WorkerHostInstance = this.HostInstance,
                        AvailableNodeCount = Interlocked.Add(ref _HandlersAvailable, 0)
                    });
                    _AvailabilityLastPublished = DateTimeOffset.Now;
                }
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }
Exemplo n.º 11
0
        public void ProcessItems()
        {
            int count = Interlocked.Decrement(ref _queuedCalls);

            // exit if there are more callbacks following us
            if (count % 10000 == 0)
            {
                _loggerRef.Target.LogDebug("ProcessItems: Queued calls remaining: {0}", count);
            }
            if (count != 0)
            {
                return;
            }
            ICoreItem item = null;

            _queuedItems.Locked(queue =>
            {
                if (queue.Count > 0)
                {
                    item = queue.Dequeue();
                }
            });
            while (item != null)
            {
                if (item.Data is QuotedAssetSet)
                {
                    var nameSpace       = item.AppProps.GetValue <string>(EnvironmentProp.NameSpace);
                    var marketName      = item.AppProps.GetValue <string>(CurveProp.MarketAndDate);
                    var curveType       = item.AppProps.GetValue <string>(CurveProp.PricingStructureType);
                    var curveName       = item.AppProps.GetValue <string>(CurveProp.CurveName);
                    var curveGenRequest = new OrdinaryCurveGenRequest
                    {
                        NameSpace   = nameSpace,
                        BaseDate    = DateTime.Now,
                        RequestId   = Guid.NewGuid().ToString(),
                        RequesterId = new UserIdentity
                        {
                            Name        = _clientRef.Target.ClientInfo.Name,
                            DisplayName = _clientRef.Target.ClientInfo.UserFullName
                        },
                        UseSavedMarketData     = true,
                        ForceGenerateEODCurves = true,
                        CurveSelector          = new[] { new CurveSelection
                                                         {
                                                             NameSpace  = nameSpace,
                                                             MarketName = marketName,
                                                             CurveType  = curveType,
                                                             CurveName  = curveName
                                                         } }
                    };
                    IWorkContext context = new WorkContext(_loggerRef.Target, _clientRef.Target, "DEV");
                    using (var workflow = new WFGenerateOrdinaryCurve())
                    {
                        workflow.Initialise(context);
                        WorkflowOutput <HandlerResponse> output = workflow.Execute(curveGenRequest);
                        WorkflowHelper.ThrowErrors(output.Errors);
                    }
                    item = null;
                    _queuedItems.Locked(queue =>
                    {
                        if (queue.Count > 0)
                        {
                            item = queue.Dequeue();
                        }
                    });
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// </summary>
        public ICoreClient Create(string instanceName)
        {
            string       cacheKey           = null;
            string       env                = null;
            string       servers            = null;
            string       protocols          = null;
            bool         debugRequests      = false;
            TimeSpan     requestTimeout     = TimeSpan.Zero;
            TimeSpan     offlineTimeout     = TimeSpan.Zero;
            CoreModeEnum coreMode           = CoreModeEnum.Standard;
            Assembly     applAssembly       = null;
            bool         useFallbackServers = true;

            //bool cacheEnabled = false;
            _factoryState.Locked(state =>
            {
                useFallbackServers = state.UseFallbackServers;
                //cacheEnabled = state.CacheEnabled;
                env            = state.Env;
                servers        = state.Servers;
                protocols      = state.Protocols;
                debugRequests  = state.DebugRequests;
                requestTimeout = state.RequestTimeout;
                offlineTimeout = state.OfflineTimeout;
                coreMode       = state.CoreMode;
                applAssembly   = state.ApplAssembly;
                cacheKey       = $"[{env}][{(protocols ?? "").ToLower()}][{(servers ?? "").ToLower()}]";
                if (state.SettingsCache.TryGetValue(cacheKey, out var cachedSettings))
                {
                    env                = cachedSettings.Env;
                    servers            = $"{cachedSettings.ServerAddress.Host}:{cachedSettings.ServerAddress.Port}";
                    protocols          = cachedSettings.ServerAddress.Protocol;
                    useFallbackServers = false;
                    debugRequests      = cachedSettings.DebugRequests;
                    requestTimeout     = cachedSettings.RequestTimeout;
                    offlineTimeout     = cachedSettings.OfflineTimeout;
                    coreMode           = cachedSettings.CoreMode;
                    applAssembly       = cachedSettings.ApplAssembly;
                    //_Logger.LogDebug("Using cached settings: {0} --> {1}://{2}", cacheKey, scheme, servers);
                }
            });
            ICoreClient client = new CoreClient(
                _loggerRef, instanceName, env, servers, protocols, useFallbackServers, debugRequests,
                requestTimeout, offlineTimeout, coreMode, applAssembly);

            // save settings
            _factoryState.Locked(state =>
            {
                state.SettingsCache[cacheKey] = new ClientSettings
                {
                    Env            = EnvHelper.EnvName(client.ClientInfo.ConfigEnv),
                    ServerAddress  = client.ServerAddress,
                    DebugRequests  = debugRequests,
                    RequestTimeout = requestTimeout,
                    OfflineTimeout = offlineTimeout,
                    CoreMode       = coreMode,
                    ApplAssembly   = applAssembly
                };
            });
            return(client);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Constructs a modifiable <see cref="NamedValueSet"/> by copying another.
 /// </summary>
 /// <param name="nvs">The NVS.</param>
 public NamedValueSet(NamedValueSet nvs)
 {
     // constructs by cloning another
     if (nvs != null)
     {
         _dict.Locked(dict =>
         {
             foreach (NamedValue nv in nvs.ToColl())
             {
                 dict[nv.Name.ToLowerInvariant()] = nv;
             }
         });
     }
 }
Exemplo n.º 14
0
        public void ProcessItems()
        {
            int count = Interlocked.Decrement(ref _queuedCalls);

            // exit if there are more callbacks following us
            //if (count % 10000 == 0)
            _loggerRef.Target.LogDebug("ProcessItems: Queued calls remaining: {0}", count);
            if (count != 0)
            {
                return;
            }
            ICoreItem item = null;

            _queuedItems.Locked(queue =>
            {
                if (queue.Count > 0)
                {
                    item = queue.Dequeue();
                }
            });
            while (item != null)
            {
                var qas = item.Data as QuotedAssetSet;
                if (qas != null)
                {
                    // 1. Get the property values that uniquely identify the curves to refresh.
                    // This is the process for the workflow request. Alternatively, a direct build of the curve can occur.
                    //
                    var nameSpace          = item.AppProps.GetValue <string>(EnvironmentProp.NameSpace);
                    var market             = item.AppProps.GetValue <string>(CurveProp.Market);//For real time use Market and not MarketAndDate
                    var curveType          = item.AppProps.GetValue <string>(CurveProp.PricingStructureType);
                    var curveName          = item.AppProps.GetValue <string>(CurveProp.CurveName);
                    var configIdentifier   = FunctionProp.Configuration + ".PricingStructures." + market + "." + curveType + "." + curveName;
                    var identifier         = FunctionProp.Market + "." + market + "." + curveType + "." + curveName;
                    List <ICoreItem> items = null;
                    // 2.Check if the dependent curves should be refreshed
                    //
                    if (chkBoxDependentCurves.Checked)
                    {
                        //Find all the QAS's where the ReferenceCurveName is equal to the curveType.curveName!
                        var requestProperties = new NamedValueSet();
                        requestProperties.Set(EnvironmentProp.NameSpace, NameSpace);
                        requestProperties.Set(CurveProp.Market, market);
                        requestProperties.Set(EnvironmentProp.Function, FunctionProp.Configuration);
                        requestProperties.Set(CurveProp.ReferenceCurveName, curveType + '.' + curveName);
                        IExpression queryExpr = Expr.BoolAND(requestProperties);
                        _loggerRef.Target.LogDebug("Dependent curve property request set at {0}", DateTime.Now.ToLongTimeString());
                        items = _cache.LoadItems <Market>(queryExpr);
                    }
                    // 3. If the build is a local build then use the curve engine.
                    //
                    if (!chkBoxWorkflow.Checked)
                    {
                        _loggerRef.Target.LogDebug("Request to build base curve {0} locally at : {1}", identifier,
                                                   DateTime.Now.ToLongTimeString());
                        var curve = CurveEngine.RefreshPricingStructureFromConfiguration(_loggerRef.Target, _cache, nameSpace, configIdentifier, identifier, qas, DateTime.Now, DateTime.Now);
                        _loggerRef.Target.LogDebug("Built the base curve {0} locally at : {1}", curve,
                                                   DateTime.Now.ToLongTimeString());
                        if (items != null)
                        {
                            foreach (var dataItem in items)
                            {
                                var spreadCurve = dataItem.Data as Market;
                                if (spreadCurve == null)
                                {
                                    continue;
                                }
                                //var bootstrap = dataItem.AppProps.GetValue<bool>(CurveProp.BootStrap, false);
                                //if (!bootstrap) { dataItem.AppProps.Set(CurveProp.BootStrap, true); }
                                try
                                {
                                    var curveId = spreadCurve.id;
                                    if (String.IsNullOrEmpty(curveId))
                                    {
                                        curveId = spreadCurve.Items[0].id;
                                        //use yieldCurve.id, CurveGen 1.X compatible
                                    }
                                    dataItem.AppProps.Set(CurveProp.BaseDate, DateTime.Now);
                                    dataItem.AppProps.Set(CurveProp.BuildDateTime, DateTime.Now);
                                    var marketData =
                                        new Pair <PricingStructure, PricingStructureValuation>(spreadCurve.Items[0],
                                                                                               spreadCurve.Items1[0]);
                                    var ps = PricingStructureFactory.Create(_loggerRef.Target, _cache, nameSpace, null, null,
                                                                            marketData, dataItem.AppProps);
                                    if (ps != null)
                                    {
                                        CurveEngine.SaveCurve(_cache, nameSpace, ps);
                                    }
                                    _loggerRef.Target.LogDebug("Built the spread curve {0} locally at : {1}",
                                                               curveId,
                                                               DateTime.Now.ToLongTimeString());
                                }
                                catch (Exception e)
                                {
                                    _loggerRef.Target.LogDebug(e.ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        // 4. Set the parameters for the work request.
                        //
                        var curveGenRequest = new OrdinaryCurveGenRequest
                        {
                            NameSpace   = nameSpace,
                            BaseDate    = DateTime.Now,
                            RequestId   = Guid.NewGuid().ToString(),
                            RequesterId = new UserIdentity
                            {
                                Name        = _cache.ClientInfo.Name,
                                DisplayName = _cache.ClientInfo.UserFullName
                                              //Name = _clientRef.Target.ClientInfo.Name,
                                              //DisplayName = _clientRef.Target.ClientInfo.UserFullName
                            },
                            UseSavedMarketData     = true,
                            ForceGenerateEODCurves = true
                        };
                        // 5. Set the base curve in the curve selection for the work request.
                        //
                        var curveSelector = new List <CurveSelection>
                        {
                            new CurveSelection
                            {
                                NameSpace  = nameSpace,
                                MarketName = market,
                                CurveType  = curveType,
                                CurveName  = curveName
                            }
                        };
                        // 6.Include all other dependent curvenames i.e. spread curves.
                        //
                        if (items != null)
                        {
                            curveSelector.AddRange(from childCurve in items
                                                   let spreadCurveType =
                                                       childCurve.AppProps.GetValue <string>(
                                                           CurveProp.PricingStructureType)
                                                       let spreadCurveName =
                                                           childCurve.AppProps.GetValue <string>(CurveProp.CurveName)
                                                           select new CurveSelection
                            {
                                NameSpace  = nameSpace,
                                MarketName = market,
                                CurveType  = spreadCurveType,
                                CurveName  = spreadCurveName
                            });
                        }
                        curveGenRequest.CurveSelector = curveSelector.ToArray();
                        // 7. Set the actual work request.
                        //
                        IWorkContext context = new WorkContext(_loggerRef.Target, _cache, "DEV");
                        //IWorkContext context = new WorkContext(_loggerRef.Target, _clientRef.Target, "DEV");
                        _loggerRef.Target.LogDebug("WorkContext set at {0}", DateTime.Now.ToLongTimeString());
                        using (var workflow = new WFGenerateOrdinaryCurve())
                        {
                            workflow.Initialise(context);
                            WorkflowOutput <HandlerResponse> output = workflow.Execute(curveGenRequest);
                            WorkflowHelper.ThrowErrors(output.Errors);
                            foreach (var error in output.Errors)
                            {
                                _loggerRef.Target.LogInfo("WorkFlow error: {0} at {1}", error.Message, DateTime.Now.ToLongTimeString());
                            }
                        }
                        _loggerRef.Target.LogDebug("WorkFlow executed at {0}", DateTime.Now.ToLongTimeString());
                        //item = null;
                        //_queuedItems.Locked(queue =>
                        //    {
                        //        if (queue.Count > 0)
                        //            item = queue.Dequeue();
                        //    });
                    }
                }
            }
        }
Exemplo n.º 15
0
        public void TestObjectLockPerformance()
        {
            bool _IsSingleCore = (Environment.ProcessorCount == 1);

            //---------------------------------------------------------------
            {
                object    target = new object();
                Stopwatch sw     = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    lock (target)
                    {
                        lockedCount++;
                    }
                }
                sw.Stop();
                Debug.Print("BenchmarkC#LockPattern : {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            // ----------- this is the lowest overhead technique ------------
            //---------------------------------------------------------------
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                int _Spinlock   = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    while (Interlocked.CompareExchange(ref _Spinlock, 1, 0) != 0)
                    {
                        if (_IsSingleCore)
                        {
                            Thread.Sleep(0);
                        }
                    }
                    try
                    {
                        lockedCount++;
                    }
                    finally
                    {
                        Interlocked.Exchange(ref _Spinlock, 0);
                    }
                }
                sw.Stop();
                Debug.Print("InlineInterlockedInt32 : {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }

            //---------------------------------------------------------------
            {
                object    target = new object();
                Stopwatch sw     = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    Monitor.Enter(target);
                    try
                    {
                        lockedCount++;
                    }
                    finally
                    {
                        Monitor.Exit(target);
                    }
                }
                sw.Stop();
                Debug.Print("SystemMonitorEnterExit : {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            {
                object    target = new object();
                Stopwatch sw     = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    int    spinCount    = 0;
                    object lockedObject = null;
                    while ((lockedObject = Interlocked.Exchange <object>(ref target, null)) == null)
                    {
                        if (_IsSingleCore)
                        {
                            Thread.Sleep(0);
                        }
                        else
                        {
                            spinCount++;
                            if (spinCount % 4000 == 0)
                            {
                                Thread.Sleep(0);
                            }
                        }
                    }
                    try
                    {
                        lockedCount++;
                    }
                    finally
                    {
                        Interlocked.Exchange <object>(ref target, lockedObject);
                    }
                }
                sw.Stop();
                Debug.Print("InlineInterlockedObject: {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            {
                SpinLock  spinlockFast = new SpinLock(false);
                Stopwatch sw           = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    bool lockTaken = false;
                    while (!lockTaken)
                    {
                        spinlockFast.Enter(ref lockTaken);
                        try
                        {
                            if (lockTaken)
                            {
                                lockedCount++;
                            }
                        }
                        finally
                        {
                            if (lockTaken)
                            {
                                spinlockFast.Exit();
                            }
                        }
                    }
                }
                sw.Stop();
                Debug.Print("Net4SpinlockPatternFast: {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            {
                SpinLock  spinlockSlow = new SpinLock(true);
                Stopwatch sw           = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    bool lockTaken = false;
                    while (!lockTaken)
                    {
                        spinlockSlow.Enter(ref lockTaken);
                        try
                        {
                            if (lockTaken)
                            {
                                lockedCount++;
                            }
                        }
                        finally
                        {
                            if (lockTaken)
                            {
                                spinlockSlow.Exit();
                            }
                        }
                    }
                }
                sw.Stop();
                Debug.Print("Net4SpinlockPatternSlow: {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            {
                object    target = new object();
                Stopwatch sw     = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    object lockedObject = ObjectLock <object> .Enter(ref target);

                    try
                    {
                        lockedCount++;
                    }
                    finally
                    {
                        ObjectLock <object> .Leave(ref target, lockedObject);
                    }
                }
                sw.Stop();
                Debug.Print("EnterLeaveCallsPattern : {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            {
                object    target = new object();
                Stopwatch sw     = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    ObjectLock <object> .Protect(ref target, delegate(object lockedObject)
                    {
                        lockedCount++;
                    });
                }
                sw.Stop();
                Debug.Print("LockedDelegatePattern  : {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
            //---------------------------------------------------------------
            {
                object           target  = new object();
                Guarded <object> wrapper = new Guarded <object>(target);
                Stopwatch        sw      = new Stopwatch();
                sw.Start();
                int lockedCount = 0;
                for (int i = 0; i < TestIterations; i++)
                {
                    //int n = (i % TargetObjects);
                    wrapper.Locked((lockedObject) =>
                    {
                        lockedCount++;
                    });
                }
                sw.Stop();
                Debug.Print("GuardedWrapperPattern  : {0} seconds, {1} locks/ms",
                            sw.Elapsed.TotalSeconds, lockedCount / sw.ElapsedMilliseconds);
            }
        }
Exemplo n.º 16
0
 public void SetValue(Guid value)
 {
     _State.Locked((state) => state.Value = value);
 }
Exemplo n.º 17
0
        private void ProcessRequests(object notUsed)
        {
            try
            {
                BasicServerState state = this.GetState();
                if (state != BasicServerState.Running)
                {
                    return;
                }

                List <InternalRequest> existingRequests  = new List <InternalRequest>();
                List <InternalRequest> receivedRequests  = new List <InternalRequest>();
                List <InternalRequest> cancelledRequests = new List <InternalRequest>();
                //Dictionary<string, InternalAvailability> availableWorkers = new Dictionary<string, InternalAvailability>();
                _State.Locked((managerState) =>
                {
                    // - process responses
                    foreach (ICoreItem item in _ManagerResponseCache.Items)
                    {
                        try
                        {
                            ManagerResponse response = (ManagerResponse)item.Data;
                            Guid requestId           = Guid.Parse(response.RequestId);
                            InternalRequest internalRequest;
                            if (!managerState.InternalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Status = response.Status;
                            managerState.InternalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process requests
                    foreach (ICoreItem item in _UnassignedRequestsCache.Items)
                    {
                        try
                        {
                            UnassignedWorkflowRequest request = (UnassignedWorkflowRequest)item.Data;
                            Guid requestId = Guid.Parse(request.RequestId);
                            InternalRequest internalRequest;
                            if (!managerState.InternalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.ExternalRequest          = request;
                            managerState.InternalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process cancellations
                    foreach (ICoreItem item in _CancellationsCache.Items)
                    {
                        try
                        {
                            CancellationRequest cancellation = (CancellationRequest)item.Data;
                            Guid requestId = Guid.Parse(cancellation.RequestId);
                            InternalRequest internalRequest;
                            if (!managerState.InternalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Cancellation             = cancellation;
                            managerState.InternalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }

                    // determine requests to be launched or cancelled
                    foreach (InternalRequest internalRequest in managerState.InternalRequests.Values)
                    {
                        if ((internalRequest.ExternalRequest != null) &&
                            ((internalRequest.Status == RequestStatusEnum.Undefined) || (internalRequest.Status == RequestStatusEnum.Received)))
                        {
                            // find requests to launch
                            if (internalRequest.Cancellation == null)
                            {
                                if (internalRequest.Status != RequestStatusEnum.Received)
                                {
                                    // new request
                                    internalRequest.Status = RequestStatusEnum.Received;
                                    receivedRequests.Add(internalRequest);
                                }
                                existingRequests.Add(internalRequest);
                            }
                            else
                            {
                                // cancelled
                                internalRequest.Status = RequestStatusEnum.Cancelled;
                                cancelledRequests.Add(internalRequest);
                            }
                        }
                    }
                });

                // publish cancelled requests
                foreach (InternalRequest request in cancelledRequests)
                {
                    PublishManagerResponse(_IntClient.Target, request);
                }

                // publish received status
                foreach (InternalRequest request in receivedRequests)
                {
                    PublishManagerResponse(_IntClient.Target, request);
                }

                // find available workers for received requests
                //Logger.LogDebug("Assigning {0} requests ...", existingRequests.Count);
                foreach (InternalRequest request in existingRequests)
                {
                    //Logger.LogDebug("----- Request: {0}", request.RequestId);
                    WorkerAvailability chosenWorker = null;
                    int highestAvailability         = 0;
                    foreach (var item in _WorkerAvailabilityCache.Items)
                    {
                        WorkerAvailability worker = (WorkerAvailability)item.Data;
                        //Logger.LogDebug("----- Worker: {0} ({1})", worker.PrivateKey, worker.AvailableNodeCount);
                        if (worker.AvailableNodeCount > highestAvailability)
                        {
                            highestAvailability = worker.AvailableNodeCount;
                            chosenWorker        = worker;
                        }
                    }
                    // exit if no workers available
                    if (chosenWorker == null)
                    {
                        break;
                    }
                    Logger.LogDebug("Assigned request '{0}' to {1} ({2})", request.RequestId, chosenWorker.PrivateKey, chosenWorker.AvailableNodeCount);
                    chosenWorker.AvailableNodeCount = chosenWorker.AvailableNodeCount - 1;
                    // publish assigned status
                    request.Status = RequestStatusEnum.Assigned;
                    PublishManagerResponse(_IntClient.Target, request);
                    // reassign to worker
                    RequestBase.TransferToWorker(_IntClient.Target, request.ExternalRequest, chosenWorker.WorkerHostComputer, chosenWorker.WorkerHostInstance);
                }
                //Logger.LogDebug("Assigned.");
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }