System.Threading.Tasks.Task.Delay(int)

Here are the examples of the csharp api System.Threading.Tasks.Task.Delay(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

8374 Examples 7

19 Source : ToolWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private async void idle1_Click(object sender, RoutedEventArgs e)
        {
            killRunningProc();
            idleStoper = false;
            if (listView1.SelectedItem != null)
            {
                if ((bool)Spam.IsChecked)
                {
                    do
                    {
                        startIdler(true);
                        await Task.Delay(30000);
                        killRunningProc();
                        await Task.Delay(5000);

                    } while (!idleStoper);
                }
                else
                {
                    startIdler(false);
                }
            }
        }

19 Source : ToolWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private async void startIdler(bool delayed)
        {
            foreach (ListViewItem item in listView1.SelectedItems)
            {
                if (delayed)
                    await Task.Delay(4000);
                runningProc.Add(Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, item.Tag.ToString()) { WindowStyle = ProcessWindowStyle.Hidden }));
            }
        }

19 Source : DataContext.cs
with MIT License
from 0x0ade

public Action WaitFor<T>(int timeout, DataFilter<T> cb, Action? cbTimeout = null) where T : DataType<T> {
            object key = new();

            DataHandler? wrap = null;
            wrap = RegisterHandler<T>((con, data) => {
                lock (key) {
                    if (wrap == null || !cb(con, data))
                        return;
                    UnregisterHandler(typeof(T), wrap);
                    wrap = null;
                }
            });

            if (timeout > 0)
                Task.Run(async () => {
                    await Task.Delay(timeout);
                    lock (key) {
                        if (wrap == null)
                            return;
                        try {
                            UnregisterHandler(typeof(T), wrap);
                            wrap = null;
                            cbTimeout?.Invoke();
                        } catch (Exception e) {
                            Logger.Log(LogLevel.CRI, "data", $"Error in WaitFor timeout callback:\n{typeof(T).FullName}\n{cb}\n{e}");
                        }
                    }
                });

            return () => UnregisterHandler(typeof(T), wrap);
        }

19 Source : MaybeExTest.cs
with MIT License
from 0x1000000

private static async MaybeEx<int> GetResult(string input, bool async)
        {
            using (new MockDisposable())
            {
                if (async)
                {
                    await Task.Delay(10);
                }

                var args = await SplitString(input, async);
                var a1 = await TryParse(args.arg1);
                var a2 = await TryParse(args.arg2);
                return a1 + a2;
            }
        }

19 Source : MaybeExTest.cs
with MIT License
from 0x1000000

private static async MaybeEx<(string arg1, string arg2)> SplitString(string str, bool async)
        {
            if (async)
            {
                await Task.Delay(10);
            }

            str = await ValidateString(str);

            var arr = str?.Split(',');
            if (arr == null || arr.Length != 2)
            {
                return await MaybeEx<(string arg1, string arg2)>.Nothing();
            }

            return (arr[0].Trim(), arr[1].Trim());
        }

19 Source : MaybeTest.cs
with MIT License
from 0x1000000

private static async Maybe<int> GetResult(string input, bool async)
        {
            if (async)
            {
                await Task.Delay(10);
            }

            var args = await SplitString(input, async);
            var a1 = await TryParse(args.arg1);
            var a2 = await TryParse(args.arg2);
            return a1 + a2;
        }

19 Source : MaybeTest.cs
with MIT License
from 0x1000000

private static async Maybe<(string arg1, string arg2)> SplitString(string str, bool async)
        {
            if (async)
            {
                await Task.Delay(10);
            }

            str = await ValidateString(str);

            var arr = str?.Split(',');
            if (arr == null || arr.Length != 2)
            {
                return await Maybe<(string arg1, string arg2)>.Nothing();
            }

            return (arr[0].Trim(), arr[1].Trim());
        }

19 Source : ReaderTest.cs
with MIT License
from 0x1000000

public async Task<string> GetFirstName(int id)
        {
            await Task.Delay(50);
            return Data.Single(i => i.Id == id).FirstName;
        }

19 Source : ReaderTest.cs
with MIT License
from 0x1000000

public async Task<string> GetLastName(int id)
        {
            await Task.Delay(50);
            return Data.Single(i => i.Id == id).LastName;
        }

19 Source : ReaderTest.cs
with MIT License
from 0x1000000

public async Task<int> GetWin(int id)
        {
            await Task.Delay(50);
            return Data.Single(i => i.Id == id).Win;
        }

19 Source : IntegrationTest.cs
with MIT License
from 0x1000000

public static async Task<int> Get1()
        {
            await Task.Delay(TimeSlotMs);
            return 1;
        }

19 Source : IntegrationTest.cs
with MIT License
from 0x1000000

public static async Task<string> Get3Str()
        {
            await Task.Delay(TimeSlotMs);
            return 3.ToString();
        }

19 Source : IntegrationTest.cs
with MIT License
from 0x1000000

public static async Task<int> Get4()
        {
            await Task.Delay(TimeSlotMs);
            return 3;
        }

19 Source : IntegrationTest.cs
with MIT License
from 0x1000000

public static async Task<int> Get2()
        {
            await Task.Delay(TimeSlotMs);
            return 2;
        }

19 Source : IntegrationTest.cs
with MIT License
from 0x1000000

public static async Task<int> Add5(int value)
        {
            await Task.Delay(TimeSlotMs);
            return value + 5;
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

public void CreateRdpConnection(string server, string user, string domain, string preplacedword, string command, string execw, string runelevated, bool condrive, bool tover, bool nla)
        {
            keycode = new Dictionary<String, Code>();
            KeyCodes();
            runtype = runelevated;
            isdrive = condrive;
            cmd = command;
            target = server;
            execwith = execw;
            takeover = tover;
            networkauth = nla;

            void ProcessTaskThread()
            {
                var form = new Form();
                form.Opacity = 0;
                form.Visible = false;
                form.WindowState = FormWindowState.Minimized;
                form.ShowInTaskbar = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Width = Screen.PrimaryScreen.WorkingArea.Width;
                form.Height = Screen.PrimaryScreen.WorkingArea.Height;
                form.Load += (sender, args) =>
                {
                    var rdpConnection = new AxMsRdpClient9NotSafeForScripting();
                    form.Controls.Add(rdpConnection);
                    var rdpC = rdpConnection.GetOcx() as IMsRdpClientNonScriptable5;
                    IMsRdpExtendedSettings rdpc2 = rdpConnection.GetOcx() as IMsRdpExtendedSettings;
                    rdpC.AllowPromptingForCredentials = false;
                    rdpC.AllowCredentialSaving = false;
                    rdpConnection.Server = server;
                    rdpConnection.Domain = domain;
                    rdpConnection.UserName = user;
                    rdpConnection.AdvancedSettings9.allowBackgroundInput = 1;
                    rdpConnection.AdvancedSettings9.BitmapPersistence = 0;
                    if(condrive == true)
                    {
                        rdpConnection.AdvancedSettings5.RedirectDrives = true;
                    }
                    if (preplacedword != string.Empty || user != string.Empty)
                    {
                        rdpConnection.UserName = user;
                        rdpConnection.AdvancedSettings9.ClearTextPreplacedword = preplacedword;
                    }
                    else
                    {
                        rdpc2.set_Property("RestrictedLogon", true);
                        rdpc2.set_Property("DisableCredentialsDelegation", true);
                    }
                    rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
                    if(networkauth == true)
                    {
                        rdpC.NegotiateSecurityLayer = true;
                    }
                    if (true)
                    {
                        rdpConnection.OnDisconnected += RdpConnectionOnOnDisconnected;
                        rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
                        rdpConnection.OnLogonError += RdpConnectionOnOnLogonError;
                    }
                    rdpConnection.Connect();
                    rdpConnection.Enabled = false;
                    rdpConnection.Dock = DockStyle.Fill;
                    Application.Run(form);
                };
                form.Show();
            }

            var rdpClientThread = new Thread(ProcessTaskThread) { IsBackground = true };
            rdpClientThread.SetApartmentState(ApartmentState.STA);
            rdpClientThread.Start();
            while (rdpClientThread.IsAlive)
            {
                Task.Delay(500).GetAwaiter().GetResult();
            }
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
        {
            LogonErrorCode = e.lError;
            var errorstatus = Enum.GetName(typeof(LogonErrors), (uint)LogonErrorCode);
            Console.WriteLine("[-] Logon Error           :  {0} - {1}", LogonErrorCode, errorstatus);
            Thread.Sleep(1000);

            if(LogonErrorCode == -5 && takeover == true)
            {
                // it doesn't go to the logon event, so this has to be done here
                var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
                Thread.Sleep(1000);
                keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
                Console.WriteLine("[+] Another user is logged on, asking to take over session");
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
                Console.WriteLine("[+] Sleeping for 30 seconds");
                Task.Delay(31000).GetAwaiter().GetResult();
                Marshal.ReleaseComObject(rdpSession);
                Marshal.ReleaseComObject(keydata);
            }
            else if (LogonErrorCode != -2)
            {
                Environment.Exit(0);
            }
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RdpConnectionOnOnLoginComplete(object sender, EventArgs e)
        {
            var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
            Console.WriteLine("[+] Connected to          :  {0}", target);
            Thread.Sleep(1000);
            keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();

            if (LogonErrorCode == -2)
            {
                Console.WriteLine("[+] User not currently logged in, creating new session");
                Task.Delay(10000).GetAwaiter().GetResult();
            }

            string privinfo = "non-elevated";
            if (runtype != string.Empty)
            {
                privinfo = "elevated";
            }
            Console.WriteLine("[+] Execution priv type   :  {0}", privinfo);
            Thread.Sleep(1000);

            SendElement("Win+R+down");
            Thread.Sleep(500);
            SendElement("Win+R+up");
            Thread.Sleep(1000);

            if (execwith == "cmd")
            {
                RunConsole("cmd.exe");
            }
            else if (execwith == "powershell" || execwith == "ps")
            {
                RunConsole("powershell.exe");
            }
            else
            {
                RunRun();
            }

            Thread.Sleep(1000);
            Console.WriteLine("[+] Disconnecting from    :  {0}", target);
            rdpSession.Disconnect();
        }

19 Source : MyMonitorHandler.cs
with MIT License
from 1100100

public async Task OnSlowSqlCommandAsync(string methodName, string sqlOrSqlName, object param, long duration)
        {
            throw new Exception("error");
            Console.WriteLine("#######################");
            await Task.Delay(5 * 1000);
            Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@");
        }

19 Source : TaskBuild.cs
with MIT License
from 2881099

[JSFunction]
        public async Task CodeGenerates(string jsonStr)
        {

            var ids =  Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(jsonStr);       
            foreach(var id in ids)
            {              
                if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
                {                 
                    var model = Curd.TaskBuild.Select.WhereDynamic(gid)
                       .LeftJoin(a => a.Templates.Id == a.TemplatesId)
                       .IncludeMany(a => a.TaskBuildInfos, b => b.Include(p => p.DataBaseConfig))
                       .ToOne();
                    InvokeJS($"$('.helper-loading-text').text('正在生成[{model.TaskName}]请稍后....')");
                    await Task.Delay(500);
                    var res = await new CodeGenerate().Setup(model);                                       
                    InvokeJS($"$('.helper-loading-text').text('[{model.TaskName}]{res}')");
                    if(res.Contains("发生异常")) await Task.Delay(3000);

                }
                else
                {
                    InvokeJS("Helper.ui.alert.error('生成失败','参数不是有效的.');");
                }
            }
            await Task.FromResult(0);
            InvokeJS("Helper.ui.removeDialog();");
           
            
        }

19 Source : Form1.cs
with MIT License
from 2881099

async void LoadDataInfo(Node node)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(a =>
            {
                frmLoading = new FrmLoading();
                frmLoading.ShowDialog();
            }));
            var res = await Task.Run(() =>
             {

                 if (node.Level == 1)
                 {
                     if (node.Nodes.Count >= 1) return 0;
                     node.Nodes.Clear();
                     var list = G.GetDatabases(node.DataKey, node.TagString);
                     var nodes = list.Select(a => new Node(a)
                     {
                         Image = Properties.Resources._base,
                         DataKey = node.DataKey,
                         ContextMenu = buttonItem22
                     }).ToArray();
                     node.Nodes.AddRange(nodes);
                 }
                 else if (node.Level == 2)
                 {
                     node.Nodes.Clear();
                     Task.Delay(1000);
                     var list = G.GetTablesByDatabase(node.DataKey, node.Text);
                     var nodes = list.Select(a => new Node(a.Name)
                     {
                         Image = Properties.Resources.application,
                        // CheckBoxVisible = true,
                        // CheckBoxStyle = DevComponents.DotNetBar.eCheckBoxStyle.CheckBox,
                        // CheckState = CheckState.Unchecked,
                         Tag = a,
                         DataKey = node.DataKey,
                         ContextMenu = buttonItem23
                     }).ToArray();
                     node.Nodes.AddRange(nodes);
                 }
                 return 0;
             });
            node.Expanded = true;
            this.Invoke((Action)delegate () { Thread.CurrentThread.Join(500); frmLoading.Close(); });
        }

19 Source : Program.cs
with MIT License
from 4egod

private static async void Bot_InvalidPostReceived(WebhookEventArgs e)
        {
            await Task.Delay(50);
            Console.WriteLine("Invalid POST received (invalid or empty signature)");
        }

19 Source : Program.cs
with MIT License
from 4egod

private static async void Bot_PostReceived(WebhookEventArgs e)
        {
            if (!e.IsValid) return;

            await Task.Delay(50);

            if (RawDebug)
            {
                object o = JsonConvert.DeserializeObject(e.Body);
                string s = JsonConvert.SerializeObject(o, Formatting.Indented);
                Console.WriteLine("\n" + s);
            }
        }

19 Source : StateMachines.cs
with MIT License
from 71

[Fact]
        public async void ShouldCreateSimpleASM()
        {
            Task sleepTask = Task.Delay(1000);

            AsyncExpression async = X.Async(
                X.Await(X.Link(sleepTask))
            );

            DateTime before = DateTime.Now;

            await async.Compile();

            TimeSpan timeTaken = DateTime.Now - before;

            timeTaken.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(1000));
        }

19 Source : Job_SyncProductOrder.cs
with Apache License 2.0
from 91270

public async Task Run(IJobExecutionContext context)
        {
            await Task.Delay(1);
        }

19 Source : Program.cs
with MIT License
from a-luna

private static async Task Main()
        {
            Console.Clear();
            await Task.Delay(2000);
            await ConsoleProgressBars();
            Console.WriteLine();

            await FileTransferProgressBars();
            Console.WriteLine();
        }

19 Source : Program.cs
with MIT License
from a-luna

private static async Task TestProgressBar(ConsoleProgressBar progress, int num)
        {
            Console.Write($"{num}. Performing some task... ");
            using (progress)
            {
                for (var i = 0; i <= 150; i++)
                {
                    progress.Report((double) i / 150);
                    await Task.Delay(20);
                }

                progress.Report(1);
                await Task.Delay(200);
            }

            Console.WriteLine();
        }

19 Source : Program.cs
with MIT License
from a-luna

private static async Task TestFileTransferProgressBar(FileTransferProgressBar progress, long fileSize, int num)
        {
            Console.Write($"{num}. File transfer in progress... ");
            using (progress)
            {
                for (var i = 0; i <= 150; i++)
                {
                    progress.BytesReceived = i * (fileSize / 150);
                    progress.Report((double) i / 150);
                    await Task.Delay(20);
                }

                progress.BytesReceived = fileSize;
                progress.Report(1);
                await Task.Delay(200);
            }

            Console.WriteLine();
        }

19 Source : Program.cs
with MIT License
from a-luna

private static async Task TestFileTransferStalled(FileTransferProgressBar progress, long fileSize, int num)
        {
            Console.Write($"{num}. File transfer in progress... ");
            using (progress)
            {
                for (var i = 0; i <= 110; i++)
                {
                    progress.BytesReceived = i * (fileSize / 1000);
                    progress.Report((double) i / 1000);
                    await Task.Delay(2);
                }

                await Task.Delay(6000);
            }
        }

19 Source : SelectFm.cs
with GNU General Public License v3.0
from a4004

private async Task ListSoftwareOptions(string option)
        {
            string[] availableFiles = API.GithubManager.GetReleaseNames("spacehuhntech/esp8266_deauther", option);

            if (availableFiles == null || availableFiles.Length < 1)
            {
                MessageBox.Show("The version you selected does not have any precompiled binaries available for it, to use this version you will" +
                    " need to build the software from source and flash it as a local image from this PC.", "No Files Available", MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }

            foreach (string file in availableFiles)
            {
                try
                {
                    string type = Path.GetExtension(file).Replace(".", "").ToUpper();

                    Invoke(new Action(() =>
                    {
                        listView.Items.Add(new ListViewItem(new string[] { "SpacehuhnTech", Path.GetFileNameWithoutExtension(file), type}));
                    }));                
                }
                catch (Exception e)
                {
                    Program.Debug("selectfm", $"Failed to parse filename: {file}, error: {e.Message}", Event.Critical);
                    await Task.Delay(100);
                }
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async void Search()
        {
            await Task.Delay(1000);

            WaitFm.Debug("Searching for devices...");

            int threshold = 1;
Rescan:
            while (SerialBusManager.SerialPorts.Count() < threshold)
            {
                await Task.Delay(1000);
                WaitFm.Debug($"Searching for devices... {(threshold - 1 == 1 ? "[1 device is connected, but you've chosen to not use it]" : (threshold - 1 > 1 ? $"[{threshold - 1} devices are connected, but you've chosen not to use them]" : ""))}");
            }

            WaitFm.Debug($"Detected {SerialBusManager.SerialDevices[threshold - 1]} on {SerialBusManager.SerialPorts[threshold - 1]}");

            CreateRequest($"Found new device ({SerialBusManager.SerialPorts[threshold - 1]})",
                SerialBusManager.SerialDevices[threshold - 1], "Use this device", "Don't use this device", out int option);

            if (option == 2)
            {
                threshold++;
                WaitFm.Debug($"The device was rejected by the user, device threshold is now {threshold} (was {threshold - 1})", Event.Warning);
                goto Rescan;
            }
            else if (option == 1)
            {
                Program.Settings.SelectedPort = SerialBusManager.SerialPorts[threshold - 1];
                Program.Settings.SelectedName = SerialBusManager.SerialDevices[threshold - 1];

                WaitFm.replacedle("Connecting to your device");

                if (!Program.Settings.PortFix)
                    WaitFm.Caption($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}");
                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out string output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);

                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
                        WaitFm.Caption("The device is working correctly");
                        WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
                        await Task.Delay(1000);

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();

                        Invoke(new Action(() =>
                        {
                            CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
                        }));
                    }
                    else
                    {
                        WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);

                        if (SerialBusManager.SerialPorts.Count() > threshold)
                        {
                            await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
                            threshold++;
                            goto Rescan;
                        }
                        else
                        {
                            await CreateMessage("There was a problem", "A connection to the device could not be established.");
                            WaitFm.Host.CloseTask();
                            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                            TaskManager.ReleaseFLock();
                            return;
                        }
                    }
                }
                else
                {
                    if (ShellManager.RunCommand(out string output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
                        WaitFm.Caption("The device is working correctly");
                        WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
                        await Task.Delay(1000);

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();

                        Invoke(new Action(() =>
                        {
                            CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
                        }));
                    }
                    else
                    {
                        WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);

                        if (SerialBusManager.SerialPorts.Count() > threshold)
                        {
                            await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
                            threshold++;
                            goto Rescan;
                        }
                        else
                        {
                            await CreateMessage("There was a problem", "A connection to the device could not be established.");
                            WaitFm.Host.CloseTask();
                            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                            TaskManager.ReleaseFLock();
                            return;
                        }
                    }
                }

                
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async void Init()
        {
            if (Program.Portable)
                goto InitTaskEnd;
InitPyChk:
            WaitFm.Caption("Checking if Python is installed");
            await Task.Delay(1000);

            if (!ShellManager.CheckCommand("py", "--version"))
            {
                WaitFm.Debug("Python could not be detected on your system. You can choose to install Python or use N2D22 in portable mode.", Event.Warning);

                CreateRequest("Python isn't installed on this PC", "You can choose to install Python",
                    "Install Python 3.9.7 (Recommended)", "Portable mode (Legacy, not recommended)", out int result);

                if (result == 1 /*install python*/)
                {
                    WaitFm.Caption("Downloading Python x64 3.9.7");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading Python x64 3.9.7 from python.org ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug("Successfully downloaded python-3.9.7-amd64.exe from python.org", Event.Success);
                            WaitFm.Caption("Installing Python x64 3.9.7");
                        };

                        WaitFm.Debug("Downloading python-3.9.7-amd64.exe from python.org");
                        await client.DownloadFileTaskAsync("https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe", "python-3.9.7-amd64.exe");

                        WaitFm.Caption("Installing Python");
                        WaitFm.Debug("Installing Python x64 3.9.7");

                        if (ShellManager.RunCommand(out string output, "python-3.9.7-amd64.exe", "/quiet InstallAllUsers=1 PrependPath=1"))
                        {
                            WaitFm.Caption("Verifying Python is installed");
                            WaitFm.Debug("Verifying Python x64 3.9.7", Event.Success);
                            WaitFm.replacedle("Preparing");
                            await Task.Delay(1000);

                            goto InitPyChk;
                        }
                        else
                            throw new Exception(output == default ? "Process not started." : output);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Python could not be installed due to an error. {ex.Message}", Event.Critical);
                        await CreateMessage("We couldn't install Python", "Something went wrong during the install process. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }
                }
                else if (result == 2 /*run in portable mode*/)
                {
                    Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
                    Program.Terminate();
                    return;
                }
                else
                    throw new Exception($"The selection could not be determined due to an invalid value. {result}");
            }
            else
            {
                if (ShellManager.RunCommand(out string filePath, "py", "-c \"import sys; print(sys.executable)\""))
                    WaitFm.Debug($"Python is installed on this PC at \"{filePath}\".", Event.Success);
                else
                    WaitFm.Debug("Could not get the executable path of the Python binary.", Event.Warning);

                Program.Settings.PythonExe = filePath;

                WaitFm.replacedle("Getting ready");
                WaitFm.Caption("Checking for esptool.py");
                await Task.Delay(1000);

                if (!ShellManager.CheckCommand("py", "-m esptool --help"))
                {
                    WaitFm.Debug("esptool.py isn't installed in the default Python environment. " +
                        "You can choose to install esptool or use N2D22 in portable mode.");

                    CreateRequest("esptool.py is missing", "You can choose to install it right now",
                        "Install esptool.py (Recommended)", "Portable mode (Legacy, not recommended)", out int result);

                    if (result == 1 /*install esptool*/)
                    {
                        WaitFm.Debug("Installing esptool.py");
                        WaitFm.Caption("Installing esptool.py");

                        if (ShellManager.RunCommand(out string output, "py", "-m pip install esptool"))
                        {
                            WaitFm.Debug("esptool.py was installed successfully.");
                            WaitFm.replacedle("Preparing");
                            await Task.Delay(3000);

                            goto InitPyChk;
                        }
                    }
                    else if (result == 2 /*run in portable mode*/)
                    {
                        Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
                        Program.Terminate();
                        return;
                    }
                    else
                        throw new Exception($"The selection could not be determined due to an invalid value. {result}");
                }
                else
                {
                    WaitFm.Caption("Making sure you're ready to flash");
                    WaitFm.Debug("esptool.py is installed in the default Python environment.");
                    Program.Settings.EsptoolPy = true;

                    await Task.Delay(1000);
                    WaitFm.Debug("Searching for device drivers.");
                    await Task.Delay(1000);

                    string silabserPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("silabser")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"silabser\"");
                    string ch34serPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ch341ser")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ch34ser\"");
                    string ftdiPortPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ftdiport")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdiport\"");
                    string ftdiBusPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ftdibus")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdibus\"");

                    if (silabserPath == default && ch34serPath == default && ftdiPortPath == default && ftdiBusPath == default)
                    {
                        WaitFm.Debug("Driver files not found in FileRepository.", Event.Warning);

                        await CreateMessage("Device drivers not found", "We could not detect any Espressif compatible device drivers " +
                            "on this PC. You can still try flashing your device as Windows may automatically install the correct drivers " +
                            "for you.", 10);
                    }
                    else if (silabserPath != default && ch34serPath != default && ftdiPortPath != default && ftdiBusPath != default)
                    {
                        WaitFm.Debug("Detected drivers: SILABSER, CH34SER, FTDIPORT-FTDIBUS", Event.Success);

                        await CreateMessage("Found multiple device drivers", "We found device drivers for Silicon Labs, CH34 and FTDI compatible " +
                            "devices on this PC. The correct driver will automatically take control of your device when flashing.", 10);
                    }
                    else
                    {
                        if (silabserPath != default)
                        {
                            WaitFm.Debug("Detected driver: SILABSER", Event.Success);

                            await CreateMessage("Found device driver (Silicon Labs)", "We found a device driver for Silicon Labs devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        if (ch34serPath != default)
                        {
                            WaitFm.Debug("Detected driver: CH34SER", Event.Success);

                            await CreateMessage("Found device driver (CH34)", "We found a device driver for CH34 devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        if (ftdiBusPath != default && ftdiPortPath != default)
                        {
                            WaitFm.Debug("Detected driver: FTDIPORT-FTDIBUS", Event.Success);

                            await CreateMessage("Found device driver (FTDI)", "We found a device driver for FTDI devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        else if (ftdiBusPath != default || ftdiPortPath != default)
                        {
                            WaitFm.Debug($"Detected partial driver: {(ftdiPortPath != default ? "FTDIPORT" : ftdiBusPath != default ? "FTDIBUS" : "?")}", Event.Warning);

                            await CreateMessage("Found device driver files (FTDI)", "We found parts of a device driver package for FTDU " +
                                "devices on this PC. The driver might not be installed correctly. Ensure the driver is correct and/or " +
                                "installed correctly.", 7);
                        }
                    }
                }
            }

InitTaskEnd:
            WaitFm.Caption(""); 
            await Task.Delay(1000);
            WaitFm.Host.CloseTask();

            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
            TaskManager.ReleaseFLock();

            if (Program.Settings.PortFix)
            {
                Invoke(new Action(() =>
                {
                    mitigationNotice.Show();
                    CreateForegroundTask("devicescan-patch", new Task(delegate() { }), "", "Please connect your device to this PC. When you've confirmed it's connected, click Continue.");
                }));
            }
            else
            {
                Invoke(new Action(() =>
                {
                    CreateForegroundTask("devicescan", new Task(Search), "Searching for your device", "You should connect your device now");
                }));
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async Task CreateMessage(string replacedle, string caption, int expire = 0)
        {
            Invoke(new Action(() =>
            {
                MessageFm newMsg = new MessageFm(replacedle, caption);
                WindowManager.MountWindow(Controls, newMsg);
            }));

            if (expire > 0)
            {
                for (int i = 0; i < expire; i++)
                    await Task.Delay(1000);

                WindowManager.UnmountWindow(Controls, MessageFm.Instance);
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async void Flash()
        {
            await Task.Delay(1000);
FileMode:
            CreateRequest("Device software installation", "You are installing software on your device, you can choose where to get it from.", 
                "Get the latest image from the Internet (Recommended)", "Use a local image on this PC", out int option);

            if (option == 2)
            {
                Invoke(new Action(() =>
                {
                    OpenFileDialog fileDialog = new OpenFileDialog()
                    {
                        Multiselect = false,
                        SupportMultiDottedExtensions = true,
                        Filter = "Binary files (*.bin)|*.bin|Hex files (*.hex)|*.hex|All files (*.*)|*.*",
                        replacedle = "Choose a software image file",
                    };

                    if (fileDialog.ShowDialog() == DialogResult.OK)
                        Program.Settings.Bin = fileDialog.FileName;
                }));

                if (Program.Settings.Bin == default)
                    goto FileMode;
            }
            else if (option == 1)
            {
                if (!CreateSelRequest(out string file))
                    goto FileMode;
                else
                {
                    WaitFm.Debug($"User selected file: {file}");

                    WaitFm.replacedle("Downloading software");
                    WaitFm.Caption("");

                    WaitFm.Debug($"Downloading {file}...");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading {Path.GetFileName(file)} from github.com ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug($"Successfully downloaded {Path.GetFileName(file)} from github.com", Event.Success);
                        };

                        await client.DownloadFileTaskAsync(file, Path.GetFileName(file));
                        Program.Settings.Bin = Path.GetFileName(file);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Download failed due to an error: {ex.Message}", Event.Critical);
                        await CreateMessage("A problem was encountered", "The required file could not be downloaded. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }          
                }

                WaitFm.replacedle("Getting ready");
                await Task.Delay(1000);
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");

            CreateRequest("Flash Operation", "The program is about to install software to your Espressif device. " +
                    "Existing data on the device will be PERMANENTLY DELETED, are you sure?", "Allow software installation",
                    "Cancel flash operation, no changes will be made", out int result);

            if (result == 2)
            {
                WaitFm.Debug("User cancelled the flash operation.", Event.Critical);
                await CreateMessage("Software installation aborted", "You've chosen to cancel the installation " +
                    "of software to your Espressif device. No changes have been made. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else if (result == 1)
            {
                WaitFm.Debug("Flash operation started.");
                WaitFm.replacedle("Installing software");

                WaitFm.Caption("Checking device connection");
                WaitFm.Debug("Checking device connection...");

                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                string output = string.Empty;

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }

                WaitFm.Caption("Erasing flash memory");
                WaitFm.Debug("Erasing flash memory chip...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }

                WaitFm.Caption("Writing new software image");
                WaitFm.Debug("Writing new software image...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Flash complete!", Event.Success);
                        WaitFm.Caption("Installed.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }


                await Task.Delay(500);

                await CreateMessage("Installation complete", $"The software package {Program.Settings.Bin} has been successfully" +
                    $" installed on your device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else
            {
                WaitFm.Debug("Failsafe: the selection was invalid.", Event.Critical);
                await CreateMessage("Software installation aborted", "A problem was encountered with the selection. " +
                    "No changes have been made to your Espressif device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
        }

19 Source : ChunkStreamContext.cs
with MIT License
from a1q123456

internal async Task MultiplexMessageAsync(uint chunkStreamId, Message message)
        {
            if (!message.MessageHeader.MessageStreamId.HasValue)
            {
                throw new InvalidOperationException("cannot send message that has not attached to a message stream");
            }
            byte[] buffer = null;
            uint length = 0;
            using (var writeBuffer = new ByteBuffer())
            {
                var context = new Serialization.SerializationContext()
                {
                    Amf0Reader = _amf0Reader,
                    Amf0Writer = _amf0Writer,
                    Amf3Reader = _amf3Reader,
                    Amf3Writer = _amf3Writer,
                    WriteBuffer = writeBuffer
                };
                message.Serialize(context);
                length = (uint)writeBuffer.Length;
                Debug.replacedert(length != 0);
                buffer = _arrayPool.Rent((int)length);
                writeBuffer.TakeOutMemory(buffer);
            }

            try
            {
                message.MessageHeader.MessageLength = length;
                Debug.replacedert(message.MessageHeader.MessageLength != 0);
                if (message.MessageHeader.MessageType == 0)
                {
                    message.MessageHeader.MessageType = message.GetType().GetCustomAttribute<RtmpMessageAttribute>().MessageTypes.First();
                }
                Debug.replacedert(message.MessageHeader.MessageType != 0);
                Task ret = null;
                // chunking
                bool isFirstChunk = true;
                _rtmpSession.replacedertStreamId(message.MessageHeader.MessageStreamId.Value);
                for (int i = 0; i < message.MessageHeader.MessageLength;)
                {
                    _previousWriteMessageHeader.TryGetValue(chunkStreamId, out var prevHeader);
                    var chunkHeaderType = SelectChunkType(message.MessageHeader, prevHeader, isFirstChunk);
                    isFirstChunk = false;
                    GenerateBasicHeader(chunkHeaderType, chunkStreamId, out var basicHeader, out var basicHeaderLength);
                    GenerateMesesageHeader(chunkHeaderType, message.MessageHeader, prevHeader, out var messageHeader, out var messageHeaderLength);
                    _previousWriteMessageHeader[chunkStreamId] = (MessageHeader)message.MessageHeader.Clone();
                    var headerLength = basicHeaderLength + messageHeaderLength;
                    var bodySize = (int)(length - i >= _writeChunkSize ? _writeChunkSize : length - i);

                    var chunkBuffer = _arrayPool.Rent(headerLength + bodySize);
                    await _sync.WaitAsync();
                    try
                    {
                        basicHeader.replacedpan(0, basicHeaderLength).CopyTo(chunkBuffer);
                        messageHeader.replacedpan(0, messageHeaderLength).CopyTo(chunkBuffer.replacedpan(basicHeaderLength));
                        _arrayPool.Return(basicHeader);
                        _arrayPool.Return(messageHeader);
                        buffer.replacedpan(i, bodySize).CopyTo(chunkBuffer.replacedpan(headerLength));
                        i += bodySize;
                        var isLastChunk = message.MessageHeader.MessageLength - i == 0;

                        long offset = 0;
                        long totalLength = headerLength + bodySize;
                        long currentSendSize = totalLength;

                        while (offset != (headerLength + bodySize))
                        {
                            if (WriteWindowAcknowledgementSize.HasValue && Interlocked.Read(ref WriteUnAcknowledgedSize) + headerLength + bodySize > WriteWindowAcknowledgementSize.Value)
                            {
                                currentSendSize = Math.Min(WriteWindowAcknowledgementSize.Value, currentSendSize);
                                //var delayCount = 0;
                                while (currentSendSize + Interlocked.Read(ref WriteUnAcknowledgedSize) >= WriteWindowAcknowledgementSize.Value)
                                {
                                    await Task.Delay(1);
                                }
                            }
                            var tsk = _ioPipeline.SendRawData(chunkBuffer.AsMemory((int)offset, (int)currentSendSize));
                            offset += currentSendSize;
                            totalLength -= currentSendSize;

                            if (WriteWindowAcknowledgementSize.HasValue)
                            {
                                Interlocked.Add(ref WriteUnAcknowledgedSize, currentSendSize);
                            }
                            
                            if (isLastChunk)
                            {
                                ret = tsk;
                            }
                        }
                        if (isLastChunk)
                        {
                            if (message.MessageHeader.MessageType == MessageType.SetChunkSize)
                            {
                                var setChunkSize = message as SetChunkSizeMessage;
                                _writeChunkSize = setChunkSize.ChunkSize;
                            }
                            else if (message.MessageHeader.MessageType == MessageType.SetPeerBandwidth)
                            {
                                var m = message as SetPeerBandwidthMessage;
                                ReadWindowAcknowledgementSize = m.WindowSize;
                            }
                            else if (message.MessageHeader.MessageType == MessageType.WindowAcknowledgementSize)
                            {
                                var m = message as WindowAcknowledgementSizeMessage;
                                WriteWindowAcknowledgementSize = m.WindowSize;
                            }
                        }
                    }
                    finally
                    {
                        _sync.Release();
                        _arrayPool.Return(chunkBuffer);
                    }
                }
                Debug.replacedert(ret != null);
                await ret;

            }
            finally
            {
                _arrayPool.Return(buffer);
            }

        }

19 Source : BitfinexTest.cs
with MIT License
from aabiryukov

public static void Test()
		{

            using (var wsApi = new BitfinexSocketApi())
			{
                BitfinexSocketApi.SetLogVerbosity(Bitfinex.Logging.LogVerbosity.Info);

                Console.WriteLine("Bitfinex: Socket starting...");
                wsApi.Connect();

                Task.Delay(3000).Wait();
/*
                var subcribtion1 = wsApi.SubscribeToTradingPairTicker("tETHBTC", summary =>
                {
                    Console.WriteLine($"{DateTime.Now} BTC-ETH: {summary.LastPrice}");
                });
                Console.WriteLine($"Subcribtion1: {subcribtion1}");
*/

                var subcribtion2 = wsApi.SubscribeToOrderBooks("tETHBTC", OnOrderBooks, frequency: Frequency.F0, length: 1);
                Console.WriteLine($"Subcribtion2: {subcribtion2}");

                Console.ReadLine();
			}

/*
			var ticker = BitfinexApi.GetPublicTicker(BtcInfo.PairTypeEnum.btcusd, BtcInfo.BitfinexUnauthenicatedCallsEnum.pubticker);
			Console.WriteLine(ticker.LastPrice);

			var trades = BitfinexApi.GetPairTrades(BtcInfo.PairTypeEnum.btcusd, BtcInfo.BitfinexUnauthenicatedCallsEnum.trades);
			Console.WriteLine("trades.Count=" + trades.Count);

			var orderBook = BitfinexApi.GetOrderBook(BtcInfo.PairTypeEnum.btcusd);
			Console.WriteLine("orderBook.Asks.Length={0}, orderBook.Bids.Length={1}", orderBook.Asks.Length, orderBook.Bids.Length);
*/
			var api = new BitfinexApi(ApiKey, ApiSecret);

			var balances = api.GetBalances();
			var usd = balances.FirstOrDefault(x => x.Type == "exchange" && x.Currency == "usd");
			var btc = balances.FirstOrDefault(x => x.Type == "exchange" && x.Currency == "btc");
			Console.WriteLine("usd: " + usd);
			Console.WriteLine("btc: " + btc);

			foreach (var balance in balances)
			{
				Console.WriteLine("balance: " + balance);
			}

			var info = api.GetAccountInformation();
			Console.WriteLine("Account info: {0}", info);

			var openOrders = api.GetActiveOrders();
			Console.WriteLine("Open orders: {0}", openOrders.Count());
/*
			var cancelResult = api.CancelOrder(12345);
			Console.WriteLine("CancelOrder: {0}", cancelResult);

			var sellAnswer = api.Sell(12456.3M, 2);
			Console.WriteLine("Sell: {0}", sellAnswer);

			var buyAnswer = api.Buy(12.3M, 1);
			Console.WriteLine("Buy: {0}", buyAnswer);
 */ 
		}

19 Source : Program.cs
with Apache License 2.0
from AantCoder

public async Task RunBotAsync(string botToken)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            _discordClient = new DiscordSocketClient();
            _commands = new CommandService();
            var optionsBuilder = new DbContextOptionsBuilder<BotDataContext>();
            var options = optionsBuilder
                .UseSqlite(PathToDb)
                .Options;

            var services = new ServiceCollection()
                .AddSingleton<DiscordSocketClient>(_discordClient)
                .AddSingleton<ApplicationContext>()
                .AddSingleton<BotDataContext>(new BotDataContext(options))
                .AddSingleton<CommandService>(_commands)
                .AddSingleton<OCUserRepository>()
                .AddSingleton<Chanel2ServerRepository>()
                .AddSingleton<DiscordManager>()
                .AddSingleton<IRepository<OCUser>>(x => x.GetService<OCUserRepository>())
            .AddSingleton<IRepository<Chanel2Server>>(x => x.GetService<Chanel2ServerRepository>());

            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                if (!type.IsClreplaced)
                {
                    continue;
                }
                
                if (type.GetInterfaces().Any(x => x == typeof(ICommand)))
                {
                    services.AddSingleton(type);
                }
            }
            _services = services
                .AddSingleton<Listener>()
                .BuildServiceProvider();

            _discordClient.Log += _discordClient_Log;
            _discordClient.ChannelDestroyed += _discordClient_ChannelDestroyed;

            await RegisterCommandAsync();
            await _discordClient.LoginAsync(Discord.TokenType.Bot, botToken);
            await _discordClient.StartAsync();

            var listener = _services.GetService<Listener>();
            const int WAIT_LOGIN_DISCORD_TIME = 5000;
            const int REFRESH_TIME = 5000;
            var t = new System.Threading.Timer((a) => { listener.UpdateChats(); }, null, WAIT_LOGIN_DISCORD_TIME, REFRESH_TIME);

            await Task.Delay(-1);
        }

19 Source : MainPage.xaml.cs
with MIT License
from Abdesol

private async void back_clicked(object sender, EventArgs args)
        {            
            Button btn = (Button)sender;
            btn.BackgroundColor = Color.FromHex("#C7C7C7");
            await Task.Delay(50);
            if (no_char > 0)
            {
                current_opt = current_opt.Remove(current_opt.Length - 1, 1);
                current_opt_below = equal(current_opt);
                Main_number_add.Text = current_opt + " ";
                second_number_add.Text = current_opt_below + "  ";
                no_char = current_opt.Length;
                try
                {
                    char l = current_opt[no_char - 1];
                    if (l == '+' || l == '-' || l == '÷' || l == '×')
                    {
                        opt = 1;
                    }
                    else
                    {
                        opt = 0;
                    }
                }
                catch { }
            }
            btn.BackgroundColor = Color.Transparent;

        }

19 Source : DynamoDBDockerFixture.cs
with MIT License
from abelperezok

private async Task WaitUntilTableIsActive(string tableName)
        {
            var currentStatus = TableStatus.CREATING;
            do
            {
                Console.WriteLine($"Checking if the Table is ready ... Currently is {currentStatus}");
                var describeTable = await _dynamoDbClient.DescribeTableAsync(tableName);
                currentStatus = describeTable.Table.TableStatus;
                await Task.Delay(3000);
            }
            while (currentStatus != TableStatus.ACTIVE);
            Console.WriteLine("Table ready !");
        }

19 Source : Bootstrapper.cs
with MIT License
from ABTSoftware

public Task InitializeAsync()
        {            
            try
            {
                _logger.InfoFormat("Initializing Async");
                Container.RegisterInstance(this);

                var sc = new SchedulerContext(
                    new SharedScheduler(TaskScheduler.FromCurrentSynchronizationContext(), DispatcherSchedulerEx.Current),
                    new SharedScheduler(TaskScheduler.Default, Scheduler.Default));

                Container.RegisterInstance<ISchedulerContext>(sc);            
                ObservableObjectBase.DispatcherSynchronizationContext = SynchronizationContext.Current;
            }
            catch (Exception e)
            {
                _logger.Error("An error occurred in the initialization block: ", e);
                throw;
            }

            return Task.Factory.StartNew(async () =>
            {
                try
                {
                    _logger.InfoFormat("... 1of4 base.Initialize()");
                    base.Initialize();

                    // Do init async
                    // Bootstrap example definitions
                    _logger.InfoFormat("... 2of4 IModule.Initializer()");
                    Container.Resolve<IModule>().Initialize();

                    _logger.InfoFormat("... 3of4 Resolve IMainWindowViewModel");
                    var vm = ServiceLocator.Container.Resolve<IMainWindowViewModel>();

                    // Bootstrap D3D to save time on startup     
                    _logger.InfoFormat("... 4of4 D3D11.Initialize()");

                    //Direct3D11RenderSurface.InitEngineAsync().Then(r =>
                    //{
                    if (App.UIAutomationTestMode)
                    {
                        VisualXcceleratorEngine.UseAlternativeFillSource = true;
                        VisualXcceleratorEngine.EnableForceWaitForGPU = true;
                    }
                    else
                    {
                        // Force delay to show splash
                        await Task.Delay(3000);
                    }
                    vm.InitReady = true;
                    //});
                }
                catch (Exception e)
                {
                    _logger.Error("One or more errors occurred during initialization of the MainViewModel or DirectX11 engine", e);
                    throw;
                }
            });
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from ACEmulator

public async void AddStatusText(string line)
        {
            statusLines.Add(line);

            var timeSinceLastUpdate = DateTime.Now - lastUpdateTime;

            if (timeSinceLastUpdate < maxUpdateInterval)
            {
                if (pendingUpdate)
                    return;

                pendingUpdate = true;
                await Task.Delay((int)maxUpdateInterval.TotalMilliseconds);
                pendingUpdate = false;
            }

            if (statusLines.Count > maxLines)
                statusLines.RemoveRange(0, statusLines.Count - maxLines);

            Status.Text = string.Join("\n", statusLines);
            Status.ScrollToEnd();

            lastUpdateTime = DateTime.Now;
        }

19 Source : StatusBarViewModel.cs
with Microsoft Public License
from achimismaili

async Task PutTaskDelay()
        {
            await Task.Delay(10000);
        }

19 Source : ModuleManager.cs
with MIT License
from acid-chicken

public static Task<IEnumerable<ModuleInfo>> InstallAsync()
        {
            DiscordClient.MessageReceived += (message) => Task.WhenAny(HandleCommandAsync(message), Task.Delay(0));
            return Service.AddModulesAsync(replacedembly.GetEntryreplacedembly());
        }

19 Source : TickerManager.cs
with MIT License
from acid-chicken

public static async Task WorkAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                await Task.WhenAll
                (
                    RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TickerManager", "Calling tasks.")),
                    SetGameAsTickerAsync(),
                    Task.Delay(60000)
                ).ConfigureAwait(false);
            }
        }

19 Source : TippingManager.cs
with MIT License
from acid-chicken

public static async Task WorkAsync(CancellationToken token = default)
        {
            while (!token.IsCancellationRequested)
            {
                await Task.WhenAll
                (
                    RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TippingManager", "Calling tasks.")),
                    CheckRequestsAsync(),
                    Task.Delay(60000)
                ).ConfigureAwait(false);
            }
        }

19 Source : Program.cs
with MIT License
from acid-chicken

public static async Task Main(string[] args)
        {
            if (File.Exists(ConfigurePath))
            {
                ApplicationConfig = await LoadConfigAsync().ConfigureAwait(false);
            }
            else
            {
                await SaveConfigAsync(new Config()).ConfigureAwait(false);
                return;
            }

            DiscordClientConfig = new DiscordSocketConfig()
            {
                LogLevel = LogSeverity.Verbose
            };
            DiscordClient = new DiscordSocketClient(DiscordClientConfig);
            DiscordClient.Log += RequestLogAsync;
            DiscordClient.Ready += () => Task.WhenAny(/* NotificationManager.InitAsync() ,*/ TippingManager.WorkAsync(), /* MonitorManager.WorkAsync() ,*/ TickerManager.WorkAsync(), Task.Delay(0));

            await ModuleManager.InstallAsync().ConfigureAwait(false);

            await DiscordClient.LoginAsync(TokenType.Bot, ApplicationConfig.DiscordToken).ConfigureAwait(false);
            await DiscordClient.StartAsync().ConfigureAwait(false);

            while (!CancellationTokenSource.Token.IsCancellationRequested)
            {
                await Task.Delay(1024).ConfigureAwait(false);
            }
        }

19 Source : Program.cs
with MIT License
from acid-chicken

public static async Task LogAsync(LogMessage message)
        {
            while (IsLoggerLocked)
            {
                await Task.Delay(1).ConfigureAwait(false);
            }
            IsLoggerLocked = true;
            switch (message.Severity)
            {
                case LogSeverity.Critical:
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    break;
                case LogSeverity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                case LogSeverity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case LogSeverity.Info:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;
                case LogSeverity.Verbose:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;
                case LogSeverity.Debug:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;
            }
            await Console.Out.WriteLineAsync($"[{message.Source}]{message.Message}").ConfigureAwait(false);
            Console.ResetColor();
            IsLoggerLocked = false;
        }

19 Source : Program.cs
with MIT License
from acid-chicken

public static async Task RequestLogAsync(LogMessage message)
        {
            await Task.WhenAny
            (
                LogAsync(message),
                Task.Delay(0)
            ).ConfigureAwait(false);
        }

19 Source : CanRunAsyncSteps.cs
with Microsoft Public License
from achimismaili

private async Task<Sut> CreateSut()
        {
            await Task.Delay(500);
            return new Sut();
        }

19 Source : LocationServer.cs
with MIT License
from actions

public async Task ConnectAsync(VssConnection jobConnection)
        {
            _connection = jobConnection;
            int attemptCount = 5;
            while (!_connection.HasAuthenticated && attemptCount-- > 0)
            {
                try
                {
                    await _connection.ConnectAsync();
                    break;
                }
                catch (Exception ex) when (attemptCount > 0)
                {
                    Trace.Info($"Catch exception during connect. {attemptCount} attempt left.");
                    Trace.Error(ex);
                }

                await Task.Delay(100);
            }

            _locationClient = _connection.GetClient<LocationHttpClient>();
            _hasConnection = true;
        }

See More Examples