当前位置: 首页>>代码示例>>C#>>正文


C# CommandProcessorContext.IsAsync方法代码示例

本文整理汇总了C#中CommandProcessorContext.IsAsync方法的典型用法代码示例。如果您正苦于以下问题:C# CommandProcessorContext.IsAsync方法的具体用法?C# CommandProcessorContext.IsAsync怎么用?C# CommandProcessorContext.IsAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CommandProcessorContext的用法示例。


在下文中一共展示了CommandProcessorContext.IsAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                    context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    context.Success();
                    conn.Close();
                },
                connectionClosed: (typedConnection, error) => context.Fail(reason: "Connection was closed prematurely."));
            context.WaitForCompletion();
            return true;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:27,代码来源:PingProcessor.cs

示例2: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            string metadata = "{'user' : 'test'}";
            var requireMaster = false;
            var data = "{'a' : 3 }";
            if (args.Length > 0)
            {
                if (args.Length != 5)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                metadata = args[3];
                requireMaster = bool.Parse(args[4]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var url = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", eventStreamId);
            context.Log.Info("Writing to {0}...", url);
            var msg = "[{'eventType': 'fooevent', 'eventId' : '" + Guid.NewGuid() + "'" + ",'data' : " + data + ", 'metadata' : " + metadata + "}]";

            var sw = Stopwatch.StartNew();
            client.Post(
                url,
                msg,
                Codec.Json.ContentType,
                new Dictionary<string, string>
                {
                        {SystemHeaders.ExpectedVersion, expectedVersion.ToString()},
                        {SystemHeaders.RequireMaster, requireMaster ? "True" : "False"}
                },
                TimeSpan.FromMilliseconds(10000),
                response =>
                {
                    sw.Stop();
                    if (response.HttpStatusCode == HttpStatusCode.Created)
                        context.Log.Info("Successfully written");
                    else
                    {
                        context.Log.Info("Error while writing: [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                        context.Log.Info("Response:\n{0}\n\n{1}\n",
                                         string.Join("\n", response.Headers.AllKeys.Select(x => string.Format("{0,-20}: {1}", x, response.Headers[x]))),
                                         response.Body);
                    }

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    context.Success();
                },
                e =>
                {
                    context.Log.ErrorException(e, "Error during POST");
                    context.Fail(e, "Error during POST.");
                });

            return true;
        }
开发者ID:kijanawoodard,项目名称:EventStore,代码行数:60,代码来源:WriteHttpProcessor.cs

示例3: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
            context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.Close();
                    context.Success();
                },
                null,
                (typedConnection, error) =>
                    {
                        if (error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });
            connection.EnqueueSend(package.AsByteArray());
            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:32,代码来源:PingProcessor.cs

示例4: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var fromOffset = 0;
            int maxRecordCount = int.MaxValue;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                {
                    context.Log.Info("More arguments: {0}", args.Length);
                    return false;
                }

                int.TryParse(args[0], out fromOffset);
                if (args.Length > 1)
                    int.TryParse(args[1], out maxRecordCount);
            }

            context.IsAsync();

            var result = _reader.ReadAll(fromOffset, maxRecordCount);
            var dataRecords = result as DataRecord[] ?? result.ToArray();
            context.Log.Info("Read {0} records{1}", dataRecords.Length, dataRecords.Length > 0 ? ":" : ".");
            foreach (var record in dataRecords)
            {
                context.Log.Info("  stream-id: {0}, data: {0}", record.Key, Encoding.UTF8.GetString(record.Data));
            }

            var nextOffset = dataRecords.Length > 0 ? dataRecords.Last().NextOffset : 0;
            context.Log.Info("Next stream offset: {0}", nextOffset);

            context.Completed();
            return true;
        }
开发者ID:AigizK,项目名称:lokad-data-platform,代码行数:34,代码来源:ReadProcessor.cs

示例5: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "default stream";
            var expectedVersion = -1;
            var data = "default-data";

            if (args.Length > 0)
            {
                if (args.Length != 3)
                {
                    context.Log.Info("More arguments: {0}",args.Length);
                    return false;
                }

                eventStreamId = args[0];
                int.TryParse(args[1], out expectedVersion);
                data = args[2];
            }

            context.IsAsync();

            context.Client.JsonClient.Post<ClientDto.WriteEvent>("/stream", new ClientDto.WriteEvent()
            {
                Data = Encoding.UTF8.GetBytes(data),
                Stream = eventStreamId,
                ExpectedVersion = expectedVersion
            });

            context.Completed();
            return true;
        }
开发者ID:AigizK,项目名称:lokad-data-platform,代码行数:31,代码来源:WriteProccessor.cs

示例6: PingFloodWaiting

        private void PingFloodWaiting(CommandProcessorContext context, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var doneEvent = new ManualResetEventSlim(false);
            var clientsDone = 0;
            long all = 0;
            for (int i = 0; i < clientsCnt; i++)
            {
                var autoResetEvent = new AutoResetEvent(false);
                var client = context.Client.CreateTcpConnection(
                    context,
                    (_, __) =>
                    {
                        Interlocked.Increment(ref all);
                        autoResetEvent.Set();
                    },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                        client.EnqueueSend(package.AsByteArray());
                        autoResetEvent.WaitOne();
                    }
                    if (Interlocked.Increment(ref clientsDone) == clientsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                }) { IsBackground = true });
            }

            var sw = Stopwatch.StartNew();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(x => x.Close());

            var reqPerSec = (all + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int) reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int) Math.Round(sw.Elapsed.TotalMilliseconds/all));

            if (Interlocked.Read(ref all) == requestsCnt)
                context.Success();
            else
                context.Fail();
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:59,代码来源:PingFloodWaitingProcessor.cs

示例7: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;
                eventStreamId = args[0];
                if (args.Length == 2)
                    expectedVersion = args[1].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
            }

            context.IsAsync();
            var sw = new Stopwatch();
            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Trying to delete event stream '{2}'...", conn.RemoteEndPoint, conn.LocalEndPoint, eventStreamId);
                    var corrid = Guid.NewGuid();
                    var deleteDto = new TcpClientMessageDto.DeleteStream(eventStreamId, expectedVersion, false);
                    var package = new TcpPackage(TcpCommand.DeleteStream, corrid, deleteDto.Serialize()).AsByteArray();
                    sw.Start();
                    conn.EnqueueSend(package);
                },
                handlePackage: (conn, pkg) =>
                {
                    sw.Stop();
                    context.Log.Info("Delete request took: {0}.", sw.Elapsed);

                    if (pkg.Command != TcpCommand.DeleteStreamCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.DeleteStreamCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("DELETED event stream {0}.", eventStreamId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                        context.Success();
                    }
                    else
                    {
                        context.Log.Info("DELETION FAILED for event stream {0}: {1} ({2}).", eventStreamId, dto.Message, dto.Result);
                        context.Fail();
                    }
                    conn.Close();
                },
                connectionClosed:(connection, error) => context.Fail(reason: "Connection was closed prematurely."));

            context.WaitForCompletion();
            return true;
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:57,代码来源:DeleteProcessor.cs

示例8: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            var data = "test-data";
            string metadata = null;

            if (args.Length > 0)
            {
                if (args.Length < 3 || args.Length > 4)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                if (args.Length == 4)
                    metadata = args[3];
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var url = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", eventStreamId);
            context.Log.Info("Writing to {0}...", url);

            var request = Codec.Xml.To(new ClientMessageDto.WriteEventText(
                    Guid.Empty, 
                    expectedVersion,
                    new[] { new ClientMessageDto.EventText(Guid.NewGuid(), "type", data, metadata) }));

            var sw = Stopwatch.StartNew();
            client.Post(
                url,
                request,
                Codec.Xml.ContentType,
                response =>
                {
                    sw.Stop();
                    if (response.HttpStatusCode == HttpStatusCode.Created)
                        context.Log.Info("Successfully written");
                    else
                        context.Log.Info("Error while writing: [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    context.Success();
                },
                e =>
                {
                    context.Log.ErrorException(e, "Error during POST");
                    context.Fail(e, "Error during POST.");
                });

            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:53,代码来源:WriteHttpProcessor.cs

示例9: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var eventNumber = 0;
            var resolveLinkTos = false;
            var requireMaster = false;

            if (args.Length > 0)
            {
                if (args.Length > 3)
                    return false;
                eventStreamId = args[0];
                if (args.Length >= 2)
                    eventNumber = int.Parse(args[1]);
                if (args.Length >= 3)
                    requireMaster = bool.Parse(args[2]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var readUrl = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/{1}?format=json", eventStreamId,
                                                                eventNumber == -1 ? "head" : eventNumber.ToString());

            context.Log.Info("[{0}]: Reading...", context.Client.HttpEndpoint);

            var sw = Stopwatch.StartNew();
            client.Get(readUrl,
                       new Dictionary<string, string>
                       {
                            {SystemHeaders.ResolveLinkTos, resolveLinkTos ? "True" : "False"},
                            {SystemHeaders.RequireMaster, requireMaster ? "True" : "False"}
                       },
                       TimeSpan.FromMilliseconds(10000),
                       response =>
                       {
                           sw.Stop();
                           context.Log.Info("[{0} ({1})]: READ events from <{2}>.",
                                            response.HttpStatusCode, response.StatusDescription, eventStreamId);
                           context.Log.Info("Response:\n{0}\n\n{1}\n",
                                            string.Join("\n", response.Headers.AllKeys.Select(x => string.Format("{0,-20}: {1}", x, response.Headers[x]))),
                                            response.Body);
                           context.Log.Info("Read request took: {0}.", sw.Elapsed);
                           context.Success();
                       },
                       e => context.Fail(e, string.Format("READ events from <{0}>: FAILED", eventStreamId)));

            return true;
        }
开发者ID:thinkbeforecoding,项目名称:EventStore,代码行数:49,代码来源:ReadHttpProcessor.cs

示例10: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            long total = 0;
            int count = 0;

            var threads = new List<Task>();

            int threadCount = 5;
            var size = 1000;

            if (args.Length > 0)
                int.TryParse(args[0], out threadCount);
            if (args.Length > 1)
                int.TryParse(args[1], out size);

            var global = Stopwatch.StartNew();
            for (int t = 0; t < threadCount; t++)
            {

                var task = Task.Factory.StartNew(() =>
                    {
                        var watch = Stopwatch.StartNew();
                        for (int i = 0; i < size; i++)
                        {
                            context.Client.JsonClient.Post<ClientDto.WriteEvent>("/stream", new ClientDto.WriteEvent()
                                {
                                    Data = Encoding.UTF8.GetBytes("This is some test message to load the server"),
                                    Stream = "name",
                                    ExpectedVersion = -1
                                });

                            //client.Get<ClientDto.WriteEvent>("/stream/name");
                        }

                        Interlocked.Add(ref total, watch.Elapsed.Ticks);
                        Interlocked.Add(ref count, size);

                    }, TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);
                threads.Add(task);
            }
            Task.WaitAll(threads.ToArray());
            context.Completed();
            context.Log.Info("{0} per second", count / global.Elapsed.TotalSeconds);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Key), (int)(count / global.Elapsed.TotalSeconds));
            return true;
        }
开发者ID:AigizK,项目名称:lokad-data-platform,代码行数:48,代码来源:WriteEventsFloodProcessor.cs

示例11: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            int subscriptionCount = 5000;

            if (args.Length > 0)
            {
                if (args.Length > 1)
                    return false;
                subscriptionCount = int.Parse(args[0]);
            }

            context.IsAsync();

            var conn = EventStoreConnection.Create(ConnectionSettings.Create()
                                                                     .UseCustomLogger(new ClientApiLoggerBridge(context.Log))
                                                                     .FailOnNoServerResponse()
                                                                     /*.EnableVerboseLogging()*/, 
                                                                     context.Client.TcpEndpoint);
            conn.Connect();

            long appearedCnt = 0;
            var sw = Stopwatch.StartNew();
            for (int i = 0; i < subscriptionCount; ++i)
            {
                conn.SubscribeToStream(
                    string.Format("stream-{0}", i),
                    false,
                    (s, e) =>
                    {
                        var c = Interlocked.Increment(ref appearedCnt);
                        if (c%1000 == 0) Console.Write('\'');
                        if (c%100000 == 0)
                        {
                            context.Log.Trace("Received total {0} events ({1} per sec)...", c, 100000.0/sw.Elapsed.TotalSeconds);
                            sw.Restart();
                        }
                    });
            }
            context.Log.Info("Subscribed to {0} streams...", subscriptionCount);
            return true;
        }
开发者ID:kijanawoodard,项目名称:EventStore,代码行数:41,代码来源:SubscriptionStressTestProcessor.cs

示例12: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var version = 0;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;

                eventStreamId = args[0];

                if (args.Length == 2)
                    version = int.Parse(args[1]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var readUrl = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/event/{1}", eventStreamId, version);

            context.Log.Info("[{0}]: Reading...", context.Client.HttpEndpoint);

            var sw = Stopwatch.StartNew();
            client.Get(readUrl,
                       response =>
                       {
                           sw.Stop();
                           context.Log.Info("READ events from <{0}>: {1}", eventStreamId, response.Body);
                           context.Log.Info("Read request took: {0}.", sw.Elapsed);
                           context.Success();
                       },
                       e => context.Fail(e, string.Format("READ events from <{0}>: FAILED", eventStreamId)));

            return true;
        }
开发者ID:vishal-h,项目名称:EventStore-1,代码行数:36,代码来源:ReadHttpProcessor.cs

示例13: WriteFlood

        private void WriteFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt, int streamsCnt, int size)
        {
            context.IsAsync();

            var doneEvent = new ManualResetEventSlim(false);
            var clients = new List<IEventStoreConnection>();
            var threads = new List<Thread>();

            long succ = 0;

            var streams = Enumerable.Range(0, streamsCnt).Select(x => Guid.NewGuid().ToString()).ToArray();
            var sw2 = new Stopwatch();
            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                var rnd = new Random();

                var settings = ConnectionSettings.Create()
                    .UseConsoleLogger()
                    .PerformOnAnyNode()
                    .LimitReconnectionsTo(10)
                    .LimitRetriesForOperationTo(10)
                    .LimitOperationsQueueTo(10000)
                    .LimitConcurrentOperationsTo(context.Client.Options.WriteWindow/clientsCnt)
                    .FailOnNoServerResponse();

                var client = EventStoreConnection.Create(settings, new Uri(string.Format("tcp://{0}:{1}", context.Client.TcpEndpoint.Address, context.Client.TcpEndpoint.Port)));
                clients.Add(client);

                threads.Add(new Thread(_ =>
                {
                    client.ErrorOccurred += (s, e) => context.Fail(e.Exception, "Error on connection");
                    client.ConnectAsync().Wait();

                    for (int j = 0; j < count; ++j)
                    {
                        var task = client.AppendToStreamAsync(streams[rnd.Next(streamsCnt)],
                                                              ExpectedVersion.Any,
                                                              new EventData(Guid.NewGuid(),
                                                                            "TakeSomeSpaceEvent",
                                                                            false,
                                                                            Common.Utils.Helper.UTF8NoBom.GetBytes("DATA" + new string('*', size)),
                                                                            Common.Utils.Helper.UTF8NoBom.GetBytes("METADATA" + new string('$', 100))));
                        task.ContinueWith(x =>
                        {
                            if (x.IsFaulted)
                            {
                                context.Fail(x.Exception.InnerException, "Error on writing operation.");
                                return;
                            }

                            var localAll = Interlocked.Increment(ref succ);
                            if (localAll % 1000 == 0) Console.Write('.');
                            if (localAll%100000 == 0)
                            {
                                var elapsed = sw2.Elapsed;
                                sw2.Restart();
                                context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s).",
                                                  localAll,
                                                  elapsed,
                                                  1000.0*100000/elapsed.TotalMilliseconds);
                            }
                            if (localAll == requestsCnt)
                            {
                                context.Success();
                                doneEvent.Set();
                            }
                        });
                    }
                }) {IsBackground = true});
            }

            var sw = Stopwatch.StartNew();
            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            clients.ForEach(x => x.Close());
            sw.Stop();

            context.Log.Info("Completed. Successes: {0}.", succ);

            var reqPerSec = (succ + 0.0) / sw.ElapsedMilliseconds * 1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", succ, sw.ElapsedMilliseconds, reqPerSec);

            var fail = requestsCnt - succ;
            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
            var failuresRate = (int) (100 * fail / (fail + succ));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt, streamsCnt, size), failuresRate);

            if (Interlocked.Read(ref succ) != requestsCnt)
                context.Fail(reason: "There were errors or not all requests completed.");
            else
//.........这里部分代码省略.........
开发者ID:danieldeb,项目名称:EventStore,代码行数:101,代码来源:WriteFloodClientApiProcessor.cs

示例14: Flood

        private void Flood(CommandProcessorContext context, 
                           string eventStreamId, 
                           int clientsCnt, 
                           int minPerSecond, 
                           int maxPerSecond, 
                           int runTimeMinutes)
        {
            context.IsAsync();

            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var doneEvent = new ManualResetEvent(false);
            var done = false;

            var succ = 0;
            var fail = 0;

            var requestsCnt = 0;

            int sent = 0;
            int received = 0;

            var watchLockRoot = new object();
            var sw = Stopwatch.StartNew();
            for (int i = 0; i < clientsCnt; i++)
            {
                var esId = eventStreamId ?? "Stream-" + Thread.CurrentThread.ManagedThreadId % 3;

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                    {
                        if (pkg.Command != TcpCommand.WriteEventsCompleted)
                        {
                            context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                            return;
                        }

                        var dto = pkg.Data.Deserialize<TcpClientMessageDto.WriteEventsCompleted>();
                        if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                        {
                            var succDone = Interlocked.Increment(ref succ);
                            if (succDone%maxPerSecond == 0)
                                Console.Write(".");

                            Interlocked.Increment(ref requestsCnt);
                        }
                        else
                            Interlocked.Increment(ref fail);

                        Interlocked.Increment(ref received);
                    },
                    connectionClosed: (conn, err) =>
                    {
                        if (!done)
                            context.Fail(reason: "Socket was closed, but not all requests were completed.");
                        else
                            context.Success();
                    });
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    var sentCount = 0;
                    var sleepTime = 0;

                    var dataSizeCoefficient = 1;
                    var currentMinute = -1;

                    while (true)
                    {
                        TimeSpan elapsed;
                        lock (watchLockRoot)
                            elapsed = sw.Elapsed;

                        if (elapsed.TotalMinutes > runTimeMinutes)
                        {
                            done = true;
                            doneEvent.Set();
                            break;
                        }

                        if (sentCount == 0)
                        {
                            int elapsedMinutesInt = (int)elapsed.TotalMinutes;
                            lock (_randomLockRoot)
                            {
                                sentCount = minPerSecond == maxPerSecond 
                                            ? maxPerSecond : _random.Next(minPerSecond, maxPerSecond);
                                dataSizeCoefficient = _random.Next(8, 256);
                            }

                            if (currentMinute != elapsedMinutesInt)
                            {
                                currentMinute = elapsedMinutesInt;
                                context.Log.Info("\nElapsed {0} of {1} minutes, sent {2}; next block coef. {3}",
                                                 elapsedMinutesInt,
                                                 runTimeMinutes,
                                                 sent,
                                                 dataSizeCoefficient);
//.........这里部分代码省略.........
开发者ID:danieldeb,项目名称:EventStore,代码行数:101,代码来源:WriteLongTermProcessor.cs

示例15: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            var data = GenerateTestData();
            string metadata = null;

            if (args.Length > 0)
            {
                if (args.Length < 3 || args.Length > 4)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                if (args.Length == 4)
                    metadata = args[3];
            }

            context.IsAsync();
            var writeDto = new TcpClientMessageDto.WriteEvents(
                eventStreamId,
                expectedVersion,
                new[]
                {
                    new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                     "JsonDataEvent",
                                                     1,0,
                                                     Helper.UTF8NoBom.GetBytes(data),
                                                     Helper.UTF8NoBom.GetBytes(metadata ?? string.Empty))
                },
                false);
            var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), writeDto.Serialize());

            var sw = new Stopwatch();
            bool dataReceived = false;

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Writing...", conn.RemoteEndPoint, conn.LocalEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    dataReceived = true;
                    sw.Stop();

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.WriteEventsCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("Successfully written. EventId: {0}.", package.CorrelationId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                    }
                    else
                    {
                        context.Log.Info("Error while writing: {0} ({1}).", dto.Message, dto.Result);
                    }

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    conn.Close();
                    context.Success();
                },
                connectionClosed: (connection, error) =>
                {
                    if (dataReceived && error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });

            context.WaitForCompletion();
            return true;
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:81,代码来源:WriteJsonProcessor.cs


注:本文中的CommandProcessorContext.IsAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。