예제 #1
0
파일: OutgoingAsync.cs 프로젝트: wandec/ice
        public new void Abort(Exception ex)
        {
            InvocationMode mode = Proxy.IceReference.InvocationMode;

            // not implemented
            Debug.Assert(mode != InvocationMode.BatchOneway && mode != InvocationMode.BatchDatagram);
            base.Abort(ex);
        }
예제 #2
0
 /// <inheritdoc/>
 public virtual ISubflowActionBuilder Run(string workflowId, InvocationMode invocationMode = InvocationMode.Synchronous)
 {
     if (string.IsNullOrWhiteSpace(workflowId))
     {
         throw new ArgumentNullException(nameof(workflowId));
     }
     return(this.Run(workflowId, null !, invocationMode));
 }
예제 #3
0
 protected void InvokeItem(Item item, InvocationMode reason)
 {
     if (InvocationMode.HasFlag(reason))
     {
         item.RaiseInvoked();
         OnItemInvoked(new ItemEventArgs <Item>(item));
     }
 }
예제 #4
0
 /// <inheritdoc/>
 public virtual ISubflowActionBuilder Run(string workflowId, string version, InvocationMode invocationMode = InvocationMode.Synchronous)
 {
     if (string.IsNullOrWhiteSpace(workflowId))
     {
         throw new ArgumentNullException(nameof(workflowId));
     }
     this.Action.Subflow = new SubflowReference(workflowId, version, invocationMode);
     return(this);
 }
예제 #5
0
        public async Task CompareInvocationSpeeds(InvocationMode invocationMode)
        {
            const int iterations = 100;

            var stopwatch = Stopwatch.StartNew();

            switch (invocationMode)
            {
            case InvocationMode.Await:
                for (var counter = 0; counter < iterations; counter++)
                {
                    await AsyncMethod();
                }
                break;

            case InvocationMode.TaskRun:
                for (var counter = 0; counter < iterations; counter++)
                {
                    Task.Run(AsyncMethod).Wait();
                }
                break;

            case InvocationMode.ThreadPool:
                for (var counter = 0; counter < iterations; counter++)
                {
                    var done = new ManualResetEvent(false);
                    ThreadPool.QueueUserWorkItem(_ => AsyncMethod().ContinueWith(t => done.Set()));
                    done.WaitOne();
                }
                break;

#if net45
            case InvocationMode.ThreadPoolUnsafe:
                for (var counter = 0; counter < iterations; counter++)
                {
                    var done = new ManualResetEvent(false);
                    ThreadPool.UnsafeQueueUserWorkItem(_ => AsyncMethod().ContinueWith(t => done.Set()), null);
                    done.WaitOne();
                }
                break;
#endif
            case InvocationMode.AsyncHelpers:
                for (var counter = 0; counter < iterations; counter++)
                {
                    AsyncHelpers.RunSync(AsyncMethod);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(invocationMode), invocationMode, null);
            }

            var elapsed = stopwatch.Elapsed;

            Console.WriteLine($"Invocation with mode = {invocationMode} took {elapsed.TotalMilliseconds:0} ms");
        }
예제 #6
0
 /// <summary>
 /// Initializes a new <see cref="SubflowReference"/>
 /// </summary>
 /// <param name="workflowId">The id of the <see cref="WorkflowDefinition"/> to run</param>
 /// <param name="version">The version of the <see cref="WorkflowDefinition"/> to run. Defaults to 'latest'</param>
 /// <param name="invocationMode">The subflow's <see cref="Sdk.InvocationMode"/>. Defaults to <see cref="InvocationMode.Synchronous"/>.</param>
 public SubflowReference(string workflowId, string version, InvocationMode invocationMode = InvocationMode.Synchronous)
     : this()
 {
     if (string.IsNullOrWhiteSpace(workflowId))
     {
         throw new ArgumentNullException(nameof(workflowId));
     }
     this.WorkflowId     = workflowId;
     this.Version        = version;
     this.InvocationMode = invocationMode;
 }
예제 #7
0
        public async Task CompareInvocationSpeeds(InvocationMode invocationMode)
        {
            const int iterations = 100;

            var stopwatch = Stopwatch.StartNew();

            switch (invocationMode)
            {
                case InvocationMode.Await:
                    for (var counter = 0; counter < iterations; counter++)
                    {
                        await AsyncMethod();
                    }
                    break;
                case InvocationMode.TaskRun:
                    for (var counter = 0; counter < iterations; counter++)
                    {
                        Task.Run(AsyncMethod).Wait();
                    }
                    break;
                case InvocationMode.ThreadPool:
                    for (var counter = 0; counter < iterations; counter++)
                    {
                        var done = new ManualResetEvent(false);
                        ThreadPool.QueueUserWorkItem(_ => AsyncMethod().ContinueWith(t => done.Set()));
                        done.WaitOne();
                    }
                    break;
                case InvocationMode.ThreadPoolUnsafe:
                    for (var counter = 0; counter < iterations; counter++)
                    {
                        var done = new ManualResetEvent(false);
                        ThreadPool.UnsafeQueueUserWorkItem(_ => AsyncMethod().ContinueWith(t => done.Set()), null);
                        done.WaitOne();
                    }
                    break;
                case InvocationMode.AsyncHelpers:
                    for (var counter = 0; counter < iterations; counter++)
                    {
                        AsyncHelpers.RunSync(AsyncMethod);
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(invocationMode), invocationMode, null);
            }

            var elapsed = stopwatch.Elapsed;

            Console.WriteLine($"Invocation with mode = {invocationMode} took {elapsed.TotalMilliseconds:0} ms");
        }
예제 #8
0
 internal static void WriteProxyData11(
     this OutputStream ostr,
     string facet,
     InvocationMode invocationMode,
     Protocol protocol,
     Encoding encoding)
 {
     Debug.Assert(ostr.Encoding == Encoding.V11);
     ostr.WriteIce1Facet(facet);
     ostr.Write(invocationMode);
     ostr.WriteBool(false); // "secure"
     ostr.Write(protocol);
     ostr.WriteByte(0);     // protocol minor
     encoding.IceWrite(ostr);
 }
예제 #9
0
파일: OutgoingAsync.cs 프로젝트: wandec/ice
        protected void Invoke(bool synchronous)
        {
            Synchronous = synchronous;
            InvocationMode mode = Proxy.IceReference.InvocationMode;

            if (mode == InvocationMode.BatchOneway || mode == InvocationMode.BatchDatagram)
            {
                Debug.Assert(false); // not implemented
                return;
            }

            if (mode == InvocationMode.Datagram && !IsOneway)
            {
                throw new InvalidOperationException("cannot make two-way call on a datagram proxy");
            }

            //
            // NOTE: invokeImpl doesn't throw so this can be called from the
            // try block with the catch block calling abort() in case of an
            // exception.
            //
            InvokeImpl(true); // userThread = true
        }
예제 #10
0
        internal static void WriteProxyData20(
            this OutputStream ostr,
            Identity identity,
            Protocol protocol,
            Encoding encoding,
            IReadOnlyList <string> location,
            InvocationMode invocationMode,
            string facet)
        {
            Debug.Assert(ostr.Encoding == Encoding.V20);

            BitSequence bitSequence = ostr.WriteBitSequence(5);

            identity.IceWrite(ostr);

            if (protocol != Protocol.Ice2)
            {
                ostr.Write(protocol);
            }
            else
            {
                bitSequence[0] = false;
            }

            if (encoding != Encoding.V20)
            {
                encoding.IceWrite(ostr);
            }
            else
            {
                bitSequence[1] = false;
            }

            if (location.Count > 0)
            {
                ostr.WriteSequence(location, OutputStream.IceWriterFromString);
            }
            else
            {
                bitSequence[2] = false;
            }

            // We only write a non-null invocation mode for ice1.
            if (protocol == Protocol.Ice1 && invocationMode != InvocationMode.Twoway)
            {
                ostr.Write(invocationMode);
            }
            else
            {
                bitSequence[3] = false;
            }

            if (facet.Length > 0)
            {
                ostr.WriteString(facet);
            }
            else
            {
                bitSequence[4] = false;
            }
        }
예제 #11
0
        internal static ScriptJob[] StartScriptJobs(IEnumerable <ScriptBlock> scriptBlock, IEnumerable <object> inputParams, InvocationMode invocationMode, RunspacePool runspacePool, bool useLocalScope)
        {
            // These parameters should already be validated in the caller method, but we check them here again just in case
            if (scriptBlock == null)
            {
                throw new ArgumentNullException("ScriptBlock");
            }
            if (scriptBlock.Count() == 0)
            {
                throw new ArgumentOutOfRangeException("ScriptBlock", "The ScriptBlock Array does not contain any data.");
            }
            if (inputParams == null)
            {
                throw new ArgumentNullException("InputParams");
            }
            if (inputParams.Count() == 0)
            {
                throw new ArgumentOutOfRangeException("InputParams", "The InputParams Array does not contain any data.");
            }
            if ((invocationMode == InvocationMode.MatchScriptToArgumentByIndex) && (scriptBlock.Count() != inputParams.Count()))
            {
                throw new ArgumentException("When InvocationMode is MatchScriptToArgumentByIndex both ScriptBlock and InputParams arrays must be of the same length.");
            }

            ScriptJob[] JobsList = null;

            if (invocationMode == InvocationMode.AllArgumentsToEachScriptBlock)
            {
                JobsList = new ScriptJob[scriptBlock.Count()];

                var sIdx = 0;
                foreach (var script in scriptBlock)
                {
                    JobsList[sIdx] = ScriptJob.StartNew(sIdx, runspacePool, script.ToString(), inputParams, useLocalScope);
                    sIdx++;
                }
            }
            else if (invocationMode == InvocationMode.OneArgumentToEachScriptBlock)
            {
                JobsList = new ScriptJob[(scriptBlock.Count() * inputParams.Count())];
                var id = 0;
                foreach (var script in scriptBlock)
                {
                    foreach (var arg in inputParams)
                    {
                        JobsList[id] = ScriptJob.StartNew(id, runspacePool, script.ToString(), new object[] { arg }, useLocalScope);
                        id++;
                    }
                }
            }
            else if (invocationMode == InvocationMode.MatchScriptToArgumentByIndex)
            {
                JobsList = new ScriptJob[scriptBlock.Count()];
                var paramArray = inputParams.ToArray();

                var spIdx = 0;
                foreach (var script in scriptBlock)
                {
                    JobsList[spIdx] = ScriptJob.StartNew(spIdx, runspacePool, script.ToString(), new object[] { paramArray[spIdx] }, useLocalScope);
                    spIdx++;
                }
            }
            else
            {
                throw new ArgumentException("Unknown InvocationMode.");
            }

            return(JobsList);
        }
예제 #12
0
 /// <summary>
 /// </summary>
 /// <param name="mode"><see cref="InvocationMode"/></param>
 public Channel(InvocationMode mode = InvocationMode.Parallel)
 {
     InvocationMode = mode;
 }
예제 #13
0
 internal static Task InvokeAsync <T>(this AsyncActionList <T> list, InvocationMode mode, T args, CancellationToken ct)
 => mode == InvocationMode.Sequential
     ? list.InvokeSequentialAsync(args, ct)
     : list.InvokeParallelAsync(args, ct);
예제 #14
0
        /// <summary>
        /// </summary>
        /// <param name="sender">メッセージの送信元。</param>
        /// <param name="initialResponses">再生したい応答。途中まで(メッセージ数に応答数が合わない・足りない)でもOK。その場合、再生中はisAutoがtrue、それ以降はisAutoがfalseになる。</param>
        /// <param name="mode"><see cref="InvocationMode"/></param>
        public ReplicableChannel(ISender <Holder <TMessage> > sender, IEnumerable <TResponse> initialResponses = null, InvocationMode mode = InvocationMode.Parallel)
        {
            var e = initialResponses?.ToArray().GetEnumerator();

            _inner = sender;
            int sequenceNumber = 0;

            _subscription = sender.Subscribe(async(message, ct) =>
            {
                sequenceNumber++;

                // 再現実行用。
                var isAuto = false;
                var array  = message.Array;
                if (array != null)
                {
                    foreach (var x in array)
                    {
                        Replicate(ref e, ref isAuto, x);
                    }
                }
                else
                {
                    var x = message.Value;
                    Replicate(ref e, ref isAuto, x);
                }

                await _handlers.InvokeAsync(mode, new ReplicableMessage <TMessage>(isAuto, sequenceNumber, message), ct);

                // 結果記憶用。
                if (array != null)
                {
                    foreach (var x in array)
                    {
                        var responsive = x as IResponsiveMessage;
                        if (responsive != null)
                        {
                            _responses.Add(new RecordedResponse <TResponse>(sequenceNumber, responsive.Address, (TResponse)responsive.Response));
                        }
                    }
                }
                else
                {
                    var x          = message.Value;
                    var responsive = x as IResponsiveMessage;
                    if (responsive != null)
                    {
                        _responses.Add(new RecordedResponse <TResponse>(sequenceNumber, responsive.Address, (TResponse)responsive.Response));
                    }
                }
            });
        }
예제 #15
0
        /// <summary>
        /// </summary>
        /// <param name="sender">メッセージ送信元。</param>
        /// <param name="beforeMessage">イベント発生前に挟みたい処理。</param>
        /// <param name="afterMessage">イベント発生後に挟みたい処理。</param>
        public LoggingChannel(ISender <T> sender, AsyncAction <T> beforeMessage, AsyncAction <T> afterMessage, InvocationMode mode = InvocationMode.Parallel)
        {
            _inner = sender;

            _subscription = _inner.Subscribe(async(x, ct) =>
            {
                if (beforeMessage != null)
                {
                    await beforeMessage(x, ct);
                }
                await _handlers.InvokeAsync(mode, x, ct);
                if (afterMessage != null)
                {
                    await afterMessage(x, ct);
                }
            });
        }
예제 #16
0
 /// <summary>
 /// Initializes a new <see cref="SubflowReference"/>
 /// </summary>
 /// <param name="workflowId">The id of the <see cref="WorkflowDefinition"/> to run</param>
 /// <param name="invocationMode">The subflow's <see cref="Sdk.InvocationMode"/>. Defaults to <see cref="InvocationMode.Synchronous"/>.</param>
 public SubflowReference(string workflowId, InvocationMode invocationMode = InvocationMode.Synchronous)
     : this(workflowId, null !, invocationMode)
예제 #17
0
파일: UriParser.cs 프로젝트: renchuanrc/ice
                         Protocol Protocol) Parse(
            string uriString,
            bool oaEndpoints,
            Communicator communicator)
        {
            Debug.Assert(IsUri(uriString));

            try
            {
                bool iceScheme = uriString.StartsWith("ice:");
                if (iceScheme && oaEndpoints)
                {
                    throw new FormatException("an object adapter endpoint supports only ice+transport URIs");
                }

                var generalOptions = new Dictionary <string, string>();
                Dictionary <string, string>?endpointOptions = iceScheme ? null : new Dictionary <string, string>();

                Uri uri = InitialParse(uriString, generalOptions, endpointOptions);

                Protocol protocol = Protocol.Ice2;
                if (generalOptions.TryGetValue("protocol", out string?protocolValue))
                {
                    protocol = ProtocolExtensions.Parse(protocolValue);
                }

                Encoding encoding = protocol.IsSupported() ? protocol.GetEncoding() : Encoding.V2_0;
                if (generalOptions.TryGetValue("encoding", out string?encodingValue))
                {
                    encoding = Encoding.Parse(encodingValue);
                }

                InvocationMode invocationMode = InvocationMode.Twoway;
                if (generalOptions.TryGetValue("invocation-mode", out string?invocationModeValue))
                {
                    if (protocol != Protocol.Ice1)
                    {
                        throw new FormatException("option `invocation-mode' requires the ice1 protocol");
                    }
                    if (oaEndpoints)
                    {
                        throw new FormatException(
                                  "option `invocation-mode' is not applicable to object adapter endpoints");
                    }
                    if (int.TryParse(invocationModeValue, out int _))
                    {
                        throw new FormatException($"invalid value `{invocationModeValue}' for invocation-mode");
                    }
                    invocationMode = Enum.Parse <InvocationMode>(invocationModeValue, ignoreCase: true);
                }

                string        facet = uri.Fragment.Length >= 2 ? Uri.UnescapeDataString(uri.Fragment.TrimStart('#')) : "";
                List <string> path  =
                    uri.AbsolutePath.TrimStart('/').Split('/').Select(s => Uri.UnescapeDataString(s)).ToList();

                List <Endpoint>?endpoints = null;

                if (endpointOptions != null) // i.e. not ice scheme
                {
                    endpoints = new List <Endpoint>
                    {
                        CreateEndpoint(communicator,
                                       oaEndpoints,
                                       endpointOptions,
                                       protocol,
                                       uri,
                                       uriString)
                    };

                    if (generalOptions.TryGetValue("alt-endpoint", out string?altEndpointValue))
                    {
                        foreach (string endpointStr in altEndpointValue.Split(','))
                        {
                            if (endpointStr.StartsWith("ice:"))
                            {
                                throw new FormatException(
                                          $"invalid URI scheme for endpoint `{endpointStr}': must be empty or ice+transport");
                            }

                            string altUriString = endpointStr;
                            if (!altUriString.StartsWith("ice+"))
                            {
                                altUriString = $"{uri.Scheme}://{altUriString}";
                            }

                            // The separator for endpoint options in alt-endpoint is $, and we replace these $ by &
                            // before sending the string the main parser (InitialParse), which uses & as separator.
                            altUriString = altUriString.Replace('$', '&');

                            // No need to clear endpointOptions before reusing it since CreateEndpoint consumes all the
                            // endpoint options
                            Debug.Assert(endpointOptions.Count == 0);
                            uri = InitialParse(altUriString, generalOptions: null, endpointOptions);

                            Debug.Assert(uri.AbsolutePath[0] == '/'); // there is always a first segment
                            if (uri.AbsolutePath.Length > 1 || uri.Fragment.Length > 0)
                            {
                                throw new FormatException(
                                          $"endpoint `{endpointStr}' must not specify a path or fragment");
                            }
                            endpoints.Add(CreateEndpoint(communicator,
                                                         oaEndpoints,
                                                         endpointOptions,
                                                         protocol,
                                                         uri,
                                                         endpointStr));
                        }
                    }
                }

                return(encoding,
                       (IReadOnlyList <Endpoint>?)endpoints ?? ImmutableArray <Endpoint> .Empty,
                       facet,
                       invocationMode,
                       path,
                       protocol);
            }
            catch (Exception ex)
            {
                // Give context to the exception.
                throw new FormatException($"failed to parse URI `{uriString}'", ex);
            }
        }
예제 #18
0
        /// <summary>
        /// Invokes multiple instances of a script in parallel.
        /// </summary>
        public static IEnumerable <ScriptJobResult> Invoke(IEnumerable <ScriptBlock> scriptBlock, IEnumerable <object> inputParams, int maxThreads, bool useLocalScope, InvocationMode invocationMode, TimeSpan?maxExecutionTime = null)
        {
            if (scriptBlock == null)
            {
                throw new ArgumentNullException("ScriptBlock");
            }
            if (scriptBlock.Count() == 0)
            {
                throw new ArgumentOutOfRangeException("ScriptBlock", "The ScriptBlock Array does not contain any data.");
            }
            if (inputParams == null)
            {
                throw new ArgumentNullException("InputParams");
            }
            if (inputParams.Count() == 0)
            {
                throw new ArgumentOutOfRangeException("InputParams", "The InputParams Array does not contain any data.");
            }
            if ((maxThreads < 1) || (maxThreads > 64))
            {
                throw new ArgumentOutOfRangeException("MaxThreads", "The MaxThreads value can be between 1 and 64.");
            }
            if ((invocationMode == InvocationMode.MatchScriptToArgumentByIndex) && (scriptBlock.Count() != inputParams.Count()))
            {
                throw new ArgumentException("When InvocationMode is MatchScriptToArgumentByIndex both ScriptBlock and InputParams arrays must be of the same length.");
            }

            var result = new List <ScriptJobResult>(inputParams.Count());

            using (var runspacePool = RunspaceFactory.CreateRunspacePool(1, maxThreads))
            {
                runspacePool.Open();

                // START JOBS
                var JobsList = StartScriptJobs(scriptBlock, inputParams, invocationMode, runspacePool, useLocalScope);

                // WAIT FOR RESULTS
                var stopWatch = System.Diagnostics.Stopwatch.StartNew();
                while (JobsList.Any(x => !x.IsResultProcessed))
                {
                    for (int i = 0; i < JobsList.Length; i++)
                    {
                        // Get the results from all jobs that have completed (successfully or not)
                        if (JobsList[i].IsResultAvailable)
                        {
                            result.Add(JobsList[i].GetResult());
                        }
                    }

                    if (JobsList.Any(x => !x.IsResultProcessed))
                    {
                        // Check if a timeout period has been reached
                        if (maxExecutionTime.HasValue && (stopWatch.ElapsedTicks > maxExecutionTime.Value.Ticks))
                        {
                            // Operation Timed Out
                            for (int i = 0; i < JobsList.Length; i++)
                            {
                                // Stop all jobs that have not yet completed
                                if (!JobsList[i].IsResultProcessed)
                                {
                                    result.Add(JobsList[i].Stop($"The operation timed out. The maximum execution time of {TimeSpanToString(maxExecutionTime.Value)} has been reached."));
                                }
                            }
                        }
                        else
                        {
                            System.Threading.Thread.Sleep(117);
                        }
                    }
                }
                stopWatch.Stop();
            }

            return(result);
        }