Beispiel #1
0
        public async Task ActiveRepositoriesChangedOrderingShouldBeCorrectAcrossThreads()
        {
            var gitExt              = new MockGitExt();
            var repoFactory         = new MockRepositoryFactory();
            var target              = CreateVSGitExt(gitExt: gitExt, repoFactory: repoFactory);
            var activeRepositories1 = CreateActiveRepositories("repo1");
            var activeRepositories2 = CreateActiveRepositories("repo2");
            var task1 = Task.Run(() => gitExt.ActiveRepositories = activeRepositories1);
            await Task.Delay(1);

            var task2 = Task.Run(() => gitExt.ActiveRepositories = activeRepositories2);

            await Task.WhenAll(task1, task2);

            target.JoinTillEmpty();

            Assert.That(target.ActiveRepositories.Single().LocalPath, Is.EqualTo("repo2"));
        }
        private static Action Run <TContext>(StatechartDefinition <TContext> definition)
            where TContext : IContext <TContext>, IXStateSerializable => () =>
        {
            Console.WriteLine(definition.AsXStateVisualizerV4Definition() + Environment.NewLine);

            var statechart = Parser.Parse(definition) as ExecutableStatechart <FetchContext>;
            var running    = Interpreter.Interpret(statechart,
                                                   new InterpreterOptions(wait: (lapse, token) =>
                                                                          Task.Delay((int)lapse.TotalMilliseconds / 1, token)));

            running.OnMacroStep += macrostep =>
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine();
                Console.WriteLine(
                    $" Statenodes: {string.Join(", ", macrostep.State.StateConfiguration.Ids)}");
                Console.WriteLine($"    Context: {macrostep.State.Context}");
                Console.WriteLine($"Next events: {string.Join(", ", running.NextEvents.Distinct())}");
                Console.ResetColor();
            };

            running.RunAsync().ContinueWith(_ => Environment.Exit(0));

            while (true)
            {
                Console.Write("@");
                var eventType = Console.ReadLine();
                switch (eventType)
                {
                case { } when eventType.StartsWith(nameof(IncrementBy)):
                    running.Send(IncrementBy(int.Parse(eventType.Substring(11))));

                    break;

                case null: break;

                default:
                    running.Send(new NamedEvent(eventType));
                    break;
                }
            }

            // ReSharper disable once FunctionNeverReturns
        };
Beispiel #3
0
    public static async Task <int> TCPingAsync(IPAddress ip, int port, int timeout = 1000, CancellationToken ct = default)
    {
        using var client = new TcpClient(ip.AddressFamily);

        var stopwatch = Stopwatch.StartNew();

        var task = client.ConnectAsync(ip, port);

        var resTask = await Task.WhenAny(task, Task.Delay(timeout, ct));

        stopwatch.Stop();
        if (resTask == task && client.Connected)
        {
            var t = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
            return(t);
        }

        return(timeout);
    }
    protected virtual async SysTask AdjacentSwapTask(TileController firstTile, TileController secondTile)
    {
        // Has the tiles move as they're swapped. Helps see if the swapping is even happening correctly.
        Vector3 firstPos  = firstTile.transform.position;
        Vector3 secondPos = secondTile.transform.position;

        float swapTimer            = 0f;
        int   untilNextFixedUpdate = (int)(SwapDuration * Time.fixedDeltaTime * 1000);

        while (swapTimer < SwapDuration)
        {
            swapTimer += Time.deltaTime;
            firstTile.transform.position = Vector3.Lerp(firstPos, secondPos,
                                                        swapTimer / SwapDuration);
            secondTile.transform.position = Vector3.Lerp(secondPos, firstPos,
                                                         swapTimer / SwapDuration);

            untilNextFixedUpdate = (int)(SwapDuration * Time.fixedDeltaTime * 1000);
            await SysTask.Delay(untilNextFixedUpdate);
        }

        SwapBoardPositions(firstTile, secondTile);
    }
Beispiel #5
0
        private void btnSend_Click(Object sender, EventArgs e)
        {
            var str = txtSend.Buffer.Text;

            if (String.IsNullOrEmpty(str))
            {
                var md = new MessageDialog(TooltipWindow,
                                           DialogFlags.DestroyWithParent, MessageType.Warning,
                                           ButtonsType.Close, "发送内容不能为空!");
                md.Run();
                md.Dispose();
                //MessageBox.Show("发送内容不能为空!", MediaTypeNames.Text);
                //txtSend.Focus();
                return;
            }

            // 多次发送
            var count = (Int32)numMutilSend.Value;
            var sleep = (Int32)numSleep.Value;
            var ths   = (Int32)numThreads.Value;

            if (count <= 0)
            {
                count = 1;
            }
            if (sleep <= 0)
            {
                sleep = 1;
            }

            SaveConfig();

            var cfg = NetConfig.Current;

            // 处理换行
            str = str.Replace("\n", "\r\n");
            var buf = cfg.HexSend ? str.ToHex() : str.GetBytes();
            var pk  = new Packet(buf);

            if (_Client != null)
            {
                if (ths <= 1)
                {
                    _Client.SendMulti(pk, count, sleep);
                }
                else
                {
                    var any  = _Client.Local.Address.IsAny();
                    var list = new List <ISocketClient>();
                    for (var i = 0; i < ths; i++)
                    {
                        var client = _Client.Remote.CreateRemote();
                        if (!any)
                        {
                            client.Local.EndPoint = new IPEndPoint(_Client.Local.Address, 2000 + i);
                        }
                        client.StatSend    = _Client.StatSend;
                        client.StatReceive = _Client.StatReceive;
                        //client.SendMulti(buf, count, sleep);

                        list.Add(client);
                    }
                    var ts = new List <Task>();
                    for (var i = 0; i < ths; i++)
                    {
                        var task = list[i].SendConcurrency(pk, count, sleep);
                        ts.Add(task);
                    }

                    _Send = TaskEx.WhenAll(ts);
                }
            }
#if !NET4
            else if (_Server != null)
            {
                TaskEx.Run(async() =>
                {
                    BizLog.Info("准备向[{0}]个客户端发送[{1}]次[{2}]的数据", _Server.SessionCount, count, buf.Length);
                    for (var i = 0; i < count && _Server != null; i++)
                    {
                        var sw = Stopwatch.StartNew();
                        var cs = await _Server.SendAllAsync(buf);
                        sw.Stop();
                        BizLog.Info("{3}/{4} 已向[{0}]个客户端发送[{1}]数据 {2:n0}ms", cs, buf.Length, sw.ElapsedMilliseconds, i + 1, count);
                        if (sleep > 0)
                        {
                            await TaskEx.Delay(sleep);
                        }
                    }
                });
            }
#endif
        }
Beispiel #6
0
 public async Task CancelImmediately()
 {
     var cancellationToken = new CancellationToken(true);
     await TaskEx.Delay(1, cancellationToken);
 }
Beispiel #7
0
 public async Task TimeSpanVersion()
 {
     await TaskEx.Delay(TimeSpan.FromMilliseconds(1));
 }
Beispiel #8
0
 public async Task CheckItDoesReturn()
 {
     await TaskEx.Delay(1);
 }
        private async Task ExecuteAsync()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsStatusbar statusBar = (IVsStatusbar)await ServiceProvider.GetServiceAsync(typeof(SVsStatusbar));

            Assumes.Present(statusBar);

            DTE dte = (DTE)await ServiceProvider.GetServiceAsync(typeof(DTE));

            Assumes.Present(dte);
            var uri = new Uri(typeof(PrQuantifierExtendMenuPackage).Assembly.CodeBase, UriKind.Absolute);

            documentEvents = dte.Events.DocumentEvents;
            documentEvents.DocumentSaved += DocumentEvents_DocumentSaved;

            var projects = SolutionProjects.Projects();

            while (true)
            {
                if ((runPrQuantifierDateTime == changedEventDateTime &&
                     runPrQuantifierDateTime != default) ||
                    projects.Count() == 0)
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(500));

                    // refresh projects list in case is still empty
                    if (projects.Count() == 0)
                    {
                        projects = SolutionProjects.Projects();
                    }

                    continue;
                }

                try
                {
                    using var process = new System.Diagnostics.Process()
                          {
                              StartInfo = new ProcessStartInfo
                              {
                                  RedirectStandardOutput = true,
                                  CreateNoWindow         = true,
                                  UseShellExecute        = false,
                                  FileName  = Path.Combine(Path.GetDirectoryName(uri.LocalPath), @"PrQuantifier\PullRequestQuantifier.Local.Client.exe"),
                                  Arguments = $"-GitRepoPath \"{projects.ElementAt(0).FullName}\" -output Detailed"
                              }
                          };

                    process.Start();
                    Print(statusBar, await ReadOutputAsync(process));

                    if (changedEventDateTime == default)
                    {
                        changedEventDateTime = DateTimeOffset.Now;
                    }

                    runPrQuantifierDateTime = changedEventDateTime;
                }
                catch (Exception ex)
                {
                    statusBar.SetText($"PrQuantifier extension has encountered an error, please report it to ... Exception {ex.Message}");
                    return;
                }
            }
        }
Beispiel #10
0
 private async Task UpdateProgression(string text, int delay = 0)
 {
     _progressLabel.Text = text;
     await Task.Delay(delay);
 }
Beispiel #11
0
            protected async Task TestInsideWaitHelperAsync()
            {
                await TaskEx.Delay(200);

                TestInsideWaitHelperAsync2().Wait();
            }
Beispiel #12
0
 protected async Task TestSpecialHelper()
 {
     await TaskEx.Delay(100);
 }
Beispiel #13
0
 protected async Task TestSleep()
 {
     await TaskEx.Delay(200);
 }
Beispiel #14
0
 protected async Task TestWaitForkingAsyncHelper()
 {
     await TaskEx.Delay(10);
 }
Beispiel #15
0
 protected async Task TestWaitMultipleAsyncHelper()
 {
     await TaskEx.WhenAll(TaskEx.Delay(1000), TestWaitMultipleAsyncHelper2());
 }
Beispiel #16
0
        private static async Task BuildImageUsingLocalSourceAsync(Options options)
        {
            Console.WriteLine($"BuildImageUsingLocalSource");
            Console.WriteLine($"  MIClientId: {options.MIClientId}");
            Console.WriteLine($"  SPClientId: {options.SPClientId}");
            Console.WriteLine($"  AzureEnvironment: {options.AzureEnvironment.Name}");
            Console.WriteLine($"  SubscriptionId: {options.SubscriptionId}");
            Console.WriteLine($"  ResourceGroupName: {options.ResourceGroupName}");
            Console.WriteLine($"  RegistryName: {options.RegistryName}");
            Console.WriteLine($"======================================================================");
            Console.WriteLine();

            var registryClient = new AzureUtility(
                options.AzureEnvironment,
                options.TenantId,
                options.SubscriptionId,
                options.MIClientId,
                options.SPClientId,
                options.SPClientSecret).RegistryClient;

            // Pack and upload the local weather service source
            var sourceDirecotry = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "WeatherService");

            Console.WriteLine($"{DateTimeOffset.Now}: Creating tarball from '{sourceDirecotry}'");

            var tarball = CreateTarballFromDirectory(sourceDirecotry);

            Console.WriteLine($"{DateTimeOffset.Now}: Created tarball '{tarball}'");

            Console.WriteLine($"{DateTimeOffset.Now}: Uploading tarball");

            var sourceUpload = await registryClient.Registries.GetBuildSourceUploadUrlAsync(
                options.ResourceGroupName,
                options.RegistryName).ConfigureAwait(false);

            using (var stream = new FileStream(tarball, FileMode.Open, FileAccess.Read))
                using (var content = new StreamContent(stream))
                    using (var httpClient = new HttpClient())
                    {
                        // NOTE: You can also use azure storage sdk to upload the file
                        content.Headers.Add("x-ms-blob-type", "BlockBlob");
                        var response = await httpClient.PutAsync(sourceUpload.UploadUrl, content).ConfigureAwait(false);

                        response.EnsureSuccessStatusCode();
                    }

            File.Delete(tarball);

            Console.WriteLine($"{DateTimeOffset.Now}: Uploaded tarball to '{sourceUpload.RelativePath}'");

            Console.WriteLine($"{DateTimeOffset.Now}: Starting new run");

            var run = await registryClient.Registries.ScheduleRunAsync(
                options.ResourceGroupName,
                options.RegistryName,
                new DockerBuildRequest
            {
                SourceLocation = sourceUpload.RelativePath,
                DockerFilePath = "Dockerfile",
                ImageNames     = new List <string> {
                    "weatherservice:{{.Run.ID}}"
                },
                IsPushEnabled      = true,
                Platform           = new PlatformProperties(OS.Linux),
                Timeout            = 60 * 10, // 10 minutes
                AgentConfiguration = new AgentProperties(cpu: 2)
            }).ConfigureAwait(false);

            Console.WriteLine($"{DateTimeOffset.Now}: Started run: '{run.RunId}'");

            Console.WriteLine($"{DateTimeOffset.Now}: Starting new run with encoded task");

            string imageName  = $"{options.RegistryName}.azurecr.io/weatherservice:latest";
            string taskString =
                $@"
version: v1.1.0
steps:
  - build: . -t {imageName}
  - push: 
    timeout: 1800
     - {imageName}";

            run = await registryClient.Registries.ScheduleRunAsync(
                options.ResourceGroupName,
                options.RegistryName,
                new EncodedTaskRunRequest
            {
                EncodedTaskContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(taskString)),
                SourceLocation     = sourceUpload.RelativePath,
                Platform           = new PlatformProperties(OS.Linux),
                Timeout            = 60 * 10, // 10 minutes
                AgentConfiguration = new AgentProperties(cpu: 2)
            }).ConfigureAwait(false);

            Console.WriteLine($"{DateTimeOffset.Now}: Started run: '{run.RunId}'");

            // Poll the run status and wait for completion
            DateTimeOffset deadline = DateTimeOffset.Now.AddMinutes(10);

            while (RunInProgress(run.Status) &&
                   deadline >= DateTimeOffset.Now)
            {
                Console.WriteLine($"{DateTimeOffset.Now}: In progress: '{run.Status}'. Wait 10 seconds");
                await Task.Delay(10000).ConfigureAwait(false);

                run = await registryClient.Runs.GetAsync(
                    options.ResourceGroupName,
                    options.RegistryName,
                    run.RunId).ConfigureAwait(false);
            }

            Console.WriteLine($"{DateTimeOffset.Now}: Run status: '{run.Status}'");

            // Download the run log
            var logResult = await registryClient.Runs.GetLogSasUrlAsync(
                options.ResourceGroupName,
                options.RegistryName,
                run.RunId).ConfigureAwait(false);

            using (var httpClient = new HttpClient())
            {
                // NOTE: You can also use azure storage sdk to download the log
                Console.WriteLine($"{DateTimeOffset.Now}: Run log: ");
                var log = await httpClient.GetStringAsync(logResult.LogLink).ConfigureAwait(false);

                Console.WriteLine(log);
            }
        }
Beispiel #17
0
 private async Task UpdateProgression(int delay = 0)
 {
     _progressBar.PerformStep();
     await Task.Delay(delay);
 }
Beispiel #18
0
        private void btnSend_Click(Object sender, EventArgs e)
        {
            var str = txtSend.Text;

            if (String.IsNullOrEmpty(str))
            {
                MessageBox.Show("发送内容不能为空!", Text);
                txtSend.Focus();
                return;
            }

            // 多次发送
            var count = (Int32)numMutilSend.Value;
            var sleep = (Int32)numSleep.Value;
            var ths   = (Int32)numThreads.Value;

            if (count <= 0)
            {
                count = 1;
            }
            if (sleep <= 0)
            {
                sleep = 1;
            }

            SaveConfig();

            var cfg = MessageConfig.Current;

            // 处理换行
            str = str.Replace("\n", "\r\n");
            var buf = cfg.HexSend ? str.ToHex() : str.GetBytes();

            // 构造消息
            var msg = _Packet.CreateMessage(buf);
            //buf = msg.ToArray();
            var pk = msg.ToPacket();

            if (_Client != null)
            {
                if (ths <= 1)
                {
                    _Client.SendMulti(pk, count, sleep);
                }
                else
                {
                    Parallel.For(0, ths, n =>
                    {
                        var client         = _Client.Remote.CreateRemote();
                        client.StatSend    = _Client.StatSend;
                        client.StatReceive = _Client.StatReceive;
                        client.SendMulti(pk, count, sleep);
                    });
                }
            }
            else if (_Server != null)
            {
                buf = pk.ToArray();
                TaskEx.Run(async() =>
                {
                    for (Int32 i = 0; i < count; i++)
                    {
                        var cs = await _Server.SendAllAsync(buf);
                        BizLog.Info("已向[{0}]个客户端发送[{1}]数据", cs, buf.Length);
                        if (sleep > 0)
                        {
                            await TaskEx.Delay(sleep);
                        }
                    }
                });
            }
        }