System.Threading.Thread.Start()

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

4175 Examples 7

19 View Source File : SteamBotController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

public static void steamLogin(String username, String preplacedword)
        {           
            workThread = new Thread(steamLogin);
            user = username;
            preplaced = preplacedword;
            workThread.Start();
        }

19 View Source File : SteamBotController.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

public static void logBotIn()
        {
            workThread = new Thread(steamLogin);
            workThread.Start();
        }

19 View Source File : LogService.cs
License : MIT License
Project Creator : 0ffffffffh

public static void Start()
        {
            IPAddress localIp = IPAddress.Parse("127.0.0.1");

            sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            localEp = new IPEndPoint(localIp, 2019);

            sock.Bind(localEp);

            logFile = new LogFileWriter("sozlukcgi-bridge");

            worker = new Thread(new ThreadStart(Recv));
            worker.Start();

        }

19 View Source File : CelesteNetClientModule.cs
License : MIT License
Project Creator : 0x0ade

public void Start() {
            if (_StartThread?.IsAlive ?? false)
                _StartThread.Join();

            lock (ClientLock) {
                CelesteNetClientContext last = Context ?? ContextLast;
                if (Client?.IsAlive ?? false)
                    Stop();

                last?.Status?.Set(null);

                Context = new(Celeste.Instance);
                ContextLast = Context;

                Context.Status.Set("Initializing...");
            }

            _StartThread = new(() => {
                CelesteNetClientContext context = Context;
                try {
                    context.Init(Settings);
                    context.Status.Set("Connecting...");
                    context.Start();
                    if (context.Status.Spin)
                        context.Status.Set("Connected", 1f);

                } catch (ThreadInterruptedException) {
                    Logger.Log(LogLevel.CRI, "clientmod", "Startup interrupted.");
                    _StartThread = null;
                    Stop();
                    context.Status.Set("Interrupted", 3f, false);

                } catch (ThreadAbortException) {
                    _StartThread = null;
                    Stop();

                } catch (Exception e) {
                    Logger.Log(LogLevel.CRI, "clientmod", $"Failed connecting:\n{e}");
                    _StartThread = null;
                    Stop();
                    context.Status.Set("Connection failed", 3f, false);

                } finally {
                    _StartThread = null;
                }
            }) {
                Name = "CelesteNet Client Start",
                IsBackground = true
            };
            _StartThread.Start();
        }

19 View Source File : CelesteNetClientRC.cs
License : MIT License
Project Creator : 0x0ade

public static void Initialize() {
            if (Listener != null)
                return;

            try {
                Listener = new();
                // Port MUST be fixed as the website expects it to be the same for everyone.
                Listener.Prefixes.Add($"http://localhost:{CelesteNetUtils.ClientRCPort}/");
                Listener.Start();
            } catch (Exception e) {
                e.LogDetailed();
                try {
                    Listener?.Stop();
                } catch { }
                return;
            }

            ListenerThread = new(ListenerLoop) {
                IsBackground = true,
                Priority = ThreadPriority.BelowNormal
            };
            ListenerThread.Start();
        }

19 View Source File : XnaToFnaExt.cs
License : zlib License
Project Creator : 0x0ade

public static Thread AsyncPipeErr(this Process p, bool nullify = false) {
            Thread t = nullify ?

                new Thread(() => {
                    try { StreamReader err = p.StandardError; while (!p.HasExited) err.ReadLine(); } catch { }
                }) {
                    Name = $"STDERR pipe thread for {p.ProcessName}",
                    IsBackground = true
                } :

                new Thread(() => {
                    try { StreamReader err = p.StandardError; while (!p.HasExited) Console.WriteLine(err.ReadLine()); } catch { }
                }) {
                    Name = $"STDERR pipe thread for {p.ProcessName}",
                    IsBackground = true
                };
            t.Start();
            return t;
        }

19 View Source File : XnaToFnaExt.cs
License : zlib License
Project Creator : 0x0ade

public static Thread AsyncPipeOut(this Process p, bool nullify = false) {
            Thread t = nullify ?

                new Thread(() => {
                    try { StreamReader @out = p.StandardOutput; while (!p.HasExited) @out.ReadLine(); } catch { }
                }) {
                    Name = $"STDOUT pipe thread for {p.ProcessName}",
                    IsBackground = true
                } :

                new Thread(() => {
                    try { StreamReader @out = p.StandardOutput; while (!p.HasExited) Console.WriteLine(@out.ReadLine()); } catch { }
                }) {
                    Name = $"STDOUT pipe thread for {p.ProcessName}",
                    IsBackground = true
                };
            t.Start();
            return t;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ApplicationExit += new EventHandler(OnApplicationExit);
            t.Start();
            using (NotifyIcon icon = new NotifyIcon())
            {
                icon.Icon = System.Drawing.Icon.ExtractreplacedociatedIcon(Application.ExecutablePath);
                icon.ContextMenu = new ContextMenu(new MenuItem[] {
                    new MenuItem("Options", (s, e) => {new Form1().Show();}),
                    new MenuItem("Exit", (s, e) => { Application.Exit(); }),
                });
                icon.Visible = true;

                Application.Run();
                icon.Visible = false;
            }
        }

19 View Source File : settings.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

private void button1_Click(object sender, EventArgs e)
        {
            try {
                SaveSettings();
                DialogResult r = MessageBox.Show("Settings were saved! Do you wish to restart the RPC now?", "Success!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if(r == DialogResult.Yes)
                {
                    FL_RPC.Stop();
                    //Give it some time to rest
                    //Thread.Sleep(2000);

                    //Reboot
                    Thread t = new Thread(FL_RPC.Init);
                    t.Start();
                }
            } catch(Exception exx)
            {
                MessageBox.Show("An error occured: " + exx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 View Source File : Demo.cs
License : MIT License
Project Creator : 0xLaileb

private void fSwitchBox_random_style_CheckedChanged()
        {
            if (fSwitchBox_random_style.Checked)
            {
                new Thread(delegate ()
                {
                    int tmp_sleep = 150;
                    fButton1.Invoke((MethodInvoker)delegate { fButton1.FButtonStyle = FC_UI.Controls.FButton.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fCheckBox1.Invoke((MethodInvoker)delegate { fCheckBox1.FCheckBoxStyle = FC_UI.Controls.FCheckBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fRadioButton1.Invoke((MethodInvoker)delegate { fRadioButton1.FRadioButtonStyle = FC_UI.Controls.FRadioButton.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fProgressBar1.Invoke((MethodInvoker)delegate { fProgressBar1.FProgressBarStyle = FC_UI.Controls.FProgressBar.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fScrollBar1.Invoke((MethodInvoker)delegate { fScrollBar1.FScrollBarStyle = FC_UI.Controls.FScrollBar.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fGroupBox1.Invoke((MethodInvoker)delegate { fGroupBox1.FGroupBoxStyle = FC_UI.Controls.FGroupBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fRichTextBox1.Invoke((MethodInvoker)delegate { fRichTextBox1.FRichTextBoxStyle = FC_UI.Controls.FRichTextBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox1.Invoke((MethodInvoker)delegate { fTextBox1.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox2.Invoke((MethodInvoker)delegate { fTextBox2.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_global_rgb.Invoke((MethodInvoker)delegate { fSwitchBox_global_rgb.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_rgb_mode.Invoke((MethodInvoker)delegate { fSwitchBox_rgb_mode.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Random; });
                }).Start();
            }
            else
            {
                new Thread(delegate ()
                {
                    int tmp_sleep = 100;
                    fButton1.Invoke((MethodInvoker)delegate { fButton1.FButtonStyle = FC_UI.Controls.FButton.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fCheckBox1.Invoke((MethodInvoker)delegate { fCheckBox1.FCheckBoxStyle = FC_UI.Controls.FCheckBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fRadioButton1.Invoke((MethodInvoker)delegate { fRadioButton1.FRadioButtonStyle = FC_UI.Controls.FRadioButton.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fProgressBar1.Invoke((MethodInvoker)delegate { fProgressBar1.FProgressBarStyle = FC_UI.Controls.FProgressBar.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fScrollBar1.Invoke((MethodInvoker)delegate
                    {
                        fScrollBar1.FScrollBarStyle = FC_UI.Controls.FScrollBar.Style.Default; fScrollBar1.OrientationValue = Orientation.Horizontal;
                    });
                    Thread.Sleep(tmp_sleep);
                    fGroupBox1.Invoke((MethodInvoker)delegate { fGroupBox1.FGroupBoxStyle = FC_UI.Controls.FGroupBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fRichTextBox1.Invoke((MethodInvoker)delegate { fRichTextBox1.FRichTextBoxStyle = FC_UI.Controls.FRichTextBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox1.Invoke((MethodInvoker)delegate { fTextBox1.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox2.Invoke((MethodInvoker)delegate { fTextBox2.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_global_rgb.Invoke((MethodInvoker)delegate { fSwitchBox_global_rgb.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_rgb_mode.Invoke((MethodInvoker)delegate { fSwitchBox_rgb_mode.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Default; });
                }).Start();
            }
        }

19 View Source File : GmicConfigDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Opacity = 0;

            if (File.Exists(GmicPath))
            {
                workerThread = new Thread(new ThreadStart(GmicThread)) { IsBackground = true };

                // The thread must use a single-threaded apartment to access the clipboard.
                workerThread.SetApartmentState(ApartmentState.STA);
                workerThread.Start();
            }
            else
            {
                ShowErrorMessage(Resources.GmicNotFound);
                DialogResult = DialogResult.Cancel;
                Close();
            }
        }

19 View Source File : Demo.cs
License : MIT License
Project Creator : 0xLaileb

private void fSwitchBox_rgb_mode_CheckedChanged()
        {
            bool tmp = fSwitchBox_rgb_mode.Checked;
            new Thread(delegate ()
            {
                fButton1.Invoke((MethodInvoker)delegate { fButton1.RGB = tmp; });
                Thread.Sleep(1000);
                fCheckBox1.Invoke((MethodInvoker)delegate { fCheckBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fRadioButton1.Invoke((MethodInvoker)delegate { fRadioButton1.RGB = tmp; });
                Thread.Sleep(1000);
                fProgressBar1.Invoke((MethodInvoker)delegate { fProgressBar1.RGB = tmp; });
                Thread.Sleep(1000);
                fScrollBar1.Invoke((MethodInvoker)delegate { fScrollBar1.RGB = tmp; });
                Thread.Sleep(1000);
                fGroupBox1.Invoke((MethodInvoker)delegate { fGroupBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fRichTextBox1.Invoke((MethodInvoker)delegate { fRichTextBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fTextBox1.Invoke((MethodInvoker)delegate { fTextBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fTextBox2.Invoke((MethodInvoker)delegate { fTextBox2.RGB = tmp; });
                Thread.Sleep(1000);
                fSwitchBox_global_rgb.Invoke((MethodInvoker)delegate { fSwitchBox_global_rgb.RGB = tmp; });
                Thread.Sleep(1000);
                fSwitchBox_random_style.Invoke((MethodInvoker)delegate { fSwitchBox_random_style.RGB = tmp; });
                Thread.Sleep(1000);
                fSwitchBox_rgb_mode.Invoke((MethodInvoker)delegate { fSwitchBox_rgb_mode.RGB = tmp; });
            }).Start();
        }

19 View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : 13xforever

private void DumpDisc(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var backgroundWorker = (BackgroundWorker)sender;
            var dumper = (Dumper)doWorkEventArgs.Argument;
            try
            {
                var threadCts = new CancellationTokenSource();
                var combinedToken = CancellationTokenSource.CreateLinkedTokenSource(threadCts.Token, dumper.Cts.Token);
                var monitor = new Thread(() =>
                                         {
                                             try
                                             {
                                                 do
                                                 {
                                                     if (dumper.TotalSectors > 0 && backgroundWorker.IsBusy && !backgroundWorker.CancellationPending)
                                                        try { backgroundWorker.ReportProgress((int)(dumper.CurrentSector * 10000L / dumper.TotalSectors), dumper); } catch { }
                                                     Task.Delay(1000, combinedToken.Token).GetAwaiter().GetResult();
                                                 } while (!combinedToken.Token.IsCancellationRequested);
                                             }
                                             catch (TaskCanceledException)
                                             {
                                             }
                                         });
                monitor.Start();
                dumper.DumpAsync(settings.OutputDir).Wait(dumper.Cts.Token);
                threadCts.Cancel();
                monitor.Join(100);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Disc dumping error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            doWorkEventArgs.Result = dumper;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void StartReceive()
    {
        try
        {
            // Start the receive thread.
            Thread recThr = new Thread(new ThreadStart(ReceiveLoop));
            recThr.Start();
        }
        catch (Exception e)
        {
            Debug.Log("Something went wrong and the socket couldn't receive");
            Debug.Log(e.ToString());
        }
    }

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY

private void button3_Click(object sender, EventArgs e)
        {
            //Crypt
            string result = Properties.Resources.stub;
            result = result.Replace("%startup%", startup.Checked.ToString().ToLower());
            result = result.Replace("%native%", native.Checked.ToString().ToLower());
            result = result.Replace("%selfinj%", si.Checked.ToString().ToLower());
            result = result.Replace("%antivm%", antivm.Checked.ToString().ToLower());
            result = result.Replace("%key%", key.Text);
            result = result.Replace("%asm%", GenerateKey());
            var providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
            CompilerResults results;
            using (var provider = new CSharpCodeProvider(providerOptions))
            {
                var Params = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, Environment.GetEnvironmentVariable("temp") + "\\Crypted.exe", true);
                if (ico !=  null)
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86 /win32icon:\"" + ico + "\"";
                else
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86";

                Params.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
                Params.Referencedreplacedemblies.Add("System.dll");
                Params.Referencedreplacedemblies.Add("System.Drawing.Dll");
                Params.Referencedreplacedemblies.Add("System.Security.Dll");
                Params.Referencedreplacedemblies.Add("System.Management.dll");

                string fname = "";
                if (punp.Checked)
                {
                    fname = Pump();
                    Params.EmbeddedResources.Add(fname); 
                }
                
                string tmp = "payload";
                File.WriteAllBytes(tmp, EncryptAES(encFile, key.Text));
                Params.EmbeddedResources.Add(tmp);
                results = provider.CompilereplacedemblyFromSource(Params, result);
                try
                {
                    File.Delete(tmp);
                    File.Delete(fname);
                }
                catch(Exception)
                {

                } 
            }
            if (results.Errors.Count == 0)
            {
                String temp = Environment.GetEnvironmentVariable("temp");
                if (obf.Checked)
                {
                   
                    File.WriteAllBytes(temp + "\\cli.exe", Properties.Resources.cli);
                    File.WriteAllBytes(temp + "\\Confuser.Core.dll", Properties.Resources.Confuser_Core);
                    File.WriteAllBytes(temp + "\\Confuser.DynCipher.dll", Properties.Resources.Confuser_DynCipher);
                    File.WriteAllBytes(temp + "\\Confuser.Protections.dll", Properties.Resources.Confuser_Protections);
                    File.WriteAllBytes(temp + "\\Confuser.Renamer.dll", Properties.Resources.Confuser_Renamer);
                    File.WriteAllBytes(temp + "\\Confuser.Runtime.dll", Properties.Resources.Confuser_Runtime);
                    File.WriteAllBytes(temp + "\\dnlib.dll", Properties.Resources.dnlib);

                    String crproj = Properties.Resources.def.Replace("%out%", Environment.CurrentDirectory);
                    crproj = crproj.Replace("%base%", temp);
                    crproj = crproj.Replace("%file%", temp + "\\Crypted.exe");
                    File.WriteAllText(temp + "\\def.crproj", crproj);

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.Arguments = "/C " + temp + "\\cli.exe " + temp + "\\def.crproj";
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = true;
                    startInfo.FileName = "cmd.exe";
                    Thread pr = new Thread(() => Process.Start(startInfo));
                    pr.Start();
                    pr.Join();
                }
                else
                {
                    String file = Environment.CurrentDirectory + "\\Crypted.exe";
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception)
                    {

                    }
                    File.Move(temp + "\\Crypted.exe", file);
                }
                    

                MessageBox.Show("Done! Check Crypted.exe in the same folder.", "Crypting", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
            foreach (CompilerError compilerError in results.Errors)
            {
                MessageBox.Show(string.Format("Error: {0}, At line {1}", compilerError.ErrorText, compilerError.Line));
            }
            
            
                
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void StartServer()
    {
        // Establish the local endpoint for the socket. 
        IPAddress ipAddress = ServerInfo.ipAddress;
        IPEndPoint localEndPoint = ServerInfo.localEP;

        Console.WriteLine("The server is running at: " + localEndPoint.Address.ToString() + " : " + localEndPoint.Port.ToString());
        Console.WriteLine("Is loopback: " + IPAddress.IsLoopback(localEndPoint.Address));

        // Create a TCP/IP socket.  
        listenerSocket = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.  
        try
        {
            listenerSocket.Bind(localEndPoint);
            listenerSocket.Listen(MaximumPlayers);

            Thread selectThr = new Thread(StartListening);
            selectThr.Start();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Application.Quit();
        }
    }

19 View Source File : Net40.cs
License : MIT License
Project Creator : 2881099

public static Task<TResult> Run<TResult>(Func<TResult> function)
        {
            var tcs = new TaskCompletionSource<TResult>();
            new Thread(() =>
            {
                try
                {
                    tcs.SetResult(function());
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            })
            { IsBackground = true }.Start();
            return tcs.Task;
        }

19 View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099

private void CheckAvailable(int interval)
        {

            new Thread(() =>
            {

                if (UnavailableException != null)
                {
                    var bgcolor = Console.BackgroundColor;
                    var forecolor = Console.ForegroundColor;
                    Console.BackgroundColor = ConsoleColor.DarkYellow;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write($"【{Policy.Name}】恢复检查时间:{DateTime.Now.AddSeconds(interval)}");
                    Console.BackgroundColor = bgcolor;
                    Console.ForegroundColor = forecolor;
                    Console.WriteLine();
                }

                while (UnavailableException != null)
                {

                    if (running == false) return;

                    Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval));

                    if (running == false) return;

                    try
                    {

                        var conn = getFree(false);
                        if (conn == null) throw new Exception($"CheckAvailable 无法获得资源,{this.Statistics}");

                        try
                        {

                            if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable 应抛出异常,代表仍然不可用。");
                            break;

                        }
                        finally
                        {

                            Return(conn);
                        }

                    }
                    catch (Exception ex)
                    {
                        var bgcolor = Console.BackgroundColor;
                        var forecolor = Console.ForegroundColor;
                        Console.BackgroundColor = ConsoleColor.DarkYellow;
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write($"【{Policy.Name}】仍然不可用,下一次恢复检查时间:{DateTime.Now.AddSeconds(interval)},错误:({ex.Message})");
                        Console.BackgroundColor = bgcolor;
                        Console.ForegroundColor = forecolor;
                        Console.WriteLine();
                    }
                }

                RestoreToAvailable();

            }).Start();
        }

19 View Source File : CSRedisClientListTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void BLPopWithKey() {
			replacedert.Null(rds.BRPop(1, "TestBLPopWithKey1", "TestBLPopWithKey2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.RPush("TestBLPopWithKey1", "testv1");
			}).Start();
			replacedert.Equal(("TestBLPopWithKey1", "testv1"), rds.BLPopWithKey(5, "TestBLPopWithKey1", "TestBLPopWithKey2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.RPush("TestBLPopWithKey2", "testv2");
			}).Start();
			replacedert.Equal(("TestBLPopWithKey2", "testv2"), rds.BLPopWithKey(5, "TestBLPopWithKey1", "TestBLPopWithKey2"));
		}

19 View Source File : CSRedisClientListTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void BLPop() {
			replacedert.Null(rds.BRPop(1, "TestBLPop1", "TestBLPop2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.RPush("TestBLPop1", "testv1");
			}).Start();
			replacedert.Equal("testv1", rds.BRPop(5, "TestBLPop1", "TestBLPop2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.RPush("TestBLPop2", "testv2");
			}).Start();
			replacedert.Equal("testv2", rds.BRPop(5, "TestBLPop1", "TestBLPop2"));
		}

19 View Source File : CSRedisClientListTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void BRPopWithKey() {
			replacedert.Null(rds.BRPop(1, "TestBRPopWithKey1", "TestBRPopWithKey2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.LPush("TestBRPopWithKey1", "testv1");
			}).Start();
			replacedert.Equal(("TestBRPopWithKey1", "testv1"), rds.BRPopWithKey(5, "TestBRPopWithKey1", "TestBRPopWithKey2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.LPush("TestBRPopWithKey2", "testv2");
			}).Start();
			replacedert.Equal(("TestBRPopWithKey2", "testv2"), rds.BRPopWithKey(5, "TestBRPopWithKey1", "TestBRPopWithKey2"));
		}

19 View Source File : CSRedisClientListTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void BRPop() {

			replacedert.Null(rds.BRPop(1, "TestBRPop1", "TestBRPop2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.LPush("TestBRPop1", "testv1");
			}).Start();
			replacedert.Equal("testv1", rds.BRPop(5, "TestBRPop1", "TestBRPop2"));

			new Thread(() => {
				Thread.CurrentThread.Join(500);
				rds.LPush("TestBRPop2", "testv2");
			}).Start();
			replacedert.Equal("testv2", rds.BRPop(5, "TestBRPop1", "TestBRPop2"));
		}

19 View Source File : SentinelAdapter.cs
License : MIT License
Project Creator : 2881099

bool RecoverySentinel()
            {
                var ing = false;
                if (RecoverySentineling == false)
                    lock (RecoverySentinelingLock)
                    {
                        if (RecoverySentineling == false)
                            RecoverySentineling = ing = true;
                    }

                if (ing)
                {
                    new Thread(() =>
                    {
                        while (true)
                        {
                            Thread.CurrentThread.Join(1000);
                            try
                            {
                                ResetSentinel();

                                if (_ib.Get(_masterHost).CheckAvailable())
                                {
                                    if (!TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{_connectionString.Host.PadRight(21)} > Redis Sentinel switch to {_masterHost}", null)))
                                        TestTrace.WriteLine($"【{_connectionString.Host}】Redis Sentinel switch to {_masterHost}", ConsoleColor.DarkGreen);

                                    RecoverySentineling = false;
                                    return;
                                }
                            }
                            catch (Exception ex21)
                            {
                                if (!TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{_connectionString.Host.PadRight(21)} > Redis Sentinel switch to {_masterHost}", null)))
                                    TestTrace.WriteLine($"【{_connectionString.Host}】Redis Sentinel: {ex21.Message}", ConsoleColor.DarkYellow);
                            }
                        }
                    }).Start();
                }
                return ing;
            }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

internal IDisposable Subscribe(bool psub, string[] channels, Action<string, string, object> handler)
            {
                if (_stoped) return new PubSubSubscribeDisposable(this, null);
                channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
                if (channels?.Any() != true) return new PubSubSubscribeDisposable(this, null);

                var id = Guid.NewGuid();
                var time = DateTime.Now;
                var regkeys = channels.Select(a => psub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                for (var a = 0; a < regkeys.Length; a++)
                {
                    ConcurrentDictionary<Guid, RegisterInfo> dict = null;
                    lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary<Guid, RegisterInfo>());
                    dict.TryAdd(id, new RegisterInfo(id, handler, time));
                }
                lock (_lock)
                    _cancels.TryAdd(id, regkeys);
                var isnew = false;
                if (IsSubscribed == false)
                {
                    lock (_lock)
                    {
                        if (IsSubscribed == false)
                        {
                            _redisSocket = _topOwner.Adapter.GetRedisSocket(null);
                            IsSubscribed = isnew = true;
                        }
                    }
                }
                if (isnew)
                {
                    new Thread(() =>
                    {
                        _redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
                        _redisSocket.ReceiveTimeout = TimeSpan.Zero;
                        var timer = new Timer(state =>
                        {
                            _topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
                            try { _redisSocket.Write("PING"); } catch { }
                        }, null, 10000, 10000);
                        var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(false);
                        while (_stoped == false)
                        {
                            RedisResult rt = null;
                            try
                            {
                                rt = _redisSocket.Read(readCmd);
                            }
                            catch
                            {
                                Thread.CurrentThread.Join(100);
                                if (_cancels.Any()) continue;
                                break;
                            }
                            var val = rt.Value as object[];
                            if (val == null) continue; //special case

                            var val1 = val[0].ConvertTo<string>();
                            switch (val1)
                            {
                                case "pong":
                                case "punsubscribe":
                                case "unsubscribe":
                                    continue;
                                case "pmessage":
                                    OnData(val[1].ConvertTo<string>(), val[2].ConvertTo<string>(), val[3]);
                                    continue;
                                case "message":
                                    OnData(null, val[1].ConvertTo<string>(), val[2]);
                                    continue;
                            }
                        }
                        timer.Dispose();
                        lock (_lock)
                        {
                            IsSubscribed = false;
                            _redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
                            _redisSocket.ReleaseSocket();
                            _redisSocket.Dispose();
                            _redisSocket = null;
                        }
                    }).Start();
                }
                Call((psub ? "PSUBSCRIBE" : "SUBSCRIBE").Input(channels));
                return new PubSubSubscribeDisposable(this, () => Cancel(id));
            }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

static ExecCmdListenResult ExecCmdListen(Action<ExecCmdListenResult, string> ondata, string cmd, string subcmd = null, params object[] parms)
		{
			var args = PrepareCmd(cmd, subcmd, parms);
			var rds = RedisSocket.GetRedisSocket();
			Resp3Helper.Write(rds.Stream, args, true);
			var rd = Resp3Helper.Read<string>(rds.Stream);
			var rt = new ExecCmdListenResult { rds = rds };
			new Thread(() =>
			{
				ondata?.Invoke(rt, rd.Value);
				while (rt._running)
				{
					try
					{
						ondata?.Invoke(rt, Resp3Helper.Read<string>(rds.Stream).Value);
					}
					catch(Exception ex)
					{
						Console.WriteLine(ex.Message);
					}
				}
			}).Start();
			return rt;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {

            for (var k = 0; k < 1; k++)
            {
                new Thread(() =>
                {
                    for (var a = 0; a < 10000; a++)
                    {
                        try
                        {
                            cli.Get(Guid.NewGuid().ToString());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        Thread.CurrentThread.Join(100);
                    }
                }).Start();
            }

            Console.ReadKey();
            return;
        }

19 View Source File : IdleBus`1.ThreadScan.cs
License : MIT License
Project Creator : 2881099

void ThreadScanWatch(ItemInfo item)
        {
            var startThread = false;
            if (_threadStarted == false)
                lock (_threadStartedLock)
                    if (_threadStarted == false)
                        startThread = _threadStarted = true;

            if (startThread)
                new Thread(() =>
                {
                    this.ThreadScanWatchHandler();
                    lock (_threadStartedLock)
                        _threadStarted = false;
                }).Start();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
            //网络出错后,断熔,后台线程定时检查恢复
            for (var k = 0; k < 1; k++)
            {
                new Thread(() =>
                {
                    for (var a = 0; a < 10000; a++)
                    {
                        try
                        {
                            cli.Get(Guid.NewGuid().ToString());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        Thread.CurrentThread.Join(100);
                    }
                }).Start();
            }

            Console.ReadKey();
            return;
        }

19 View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099

private void CheckAvailable(int interval)
        {

            new Thread(() =>
            {

                if (UnavailableException != null)
                    TestTrace.WriteLine($"【{Policy.Name}】Next recovery time:{DateTime.Now.AddSeconds(interval)}", ConsoleColor.DarkYellow);

                while (UnavailableException != null)
                {

                    if (running == false) return;

                    Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval));

                    if (running == false) return;

                    try
                    {

                        var conn = GetFree(false);
                        if (conn == null) throw new Exception($"CheckAvailable: Failed to get resource {this.Statistics}");

                        try
                        {

                            if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable: An exception needs to be thrown");
                            break;

                        }
                        finally
                        {

                            Return(conn);
                        }

                    }
                    catch (Exception ex)
                    {
                        TestTrace.WriteLine($"【{Policy.Name}】Next recovery time: {DateTime.Now.AddSeconds(interval)} ({ex.Message})", ConsoleColor.DarkYellow);
                    }
                }

                RestoreToAvailable();

            }).Start();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
			if (args != null && args.Length == 0) args = new[] { "?" };

			ManualResetEvent wait = new ManualResetEvent(false);
			new Thread(() => {
				Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(10));

                try
                {
                    ConsoleApp app = new ConsoleApp(args, wait);
                }
                finally
                {
                    wait.Set();
                }
			}).Start();
			wait.WaitOne();
			return;
		}

19 View Source File : ListsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void BLPop()
        {
            replacedert.Null(cli.BRPop(new[] { "TestBLPop1", "TestBLPop2" }, 1));

            new Thread(() =>
            {
                Thread.CurrentThread.Join(500);
                cli.RPush("TestBLPop1", "testv1");
            }).Start();
            replacedert.Equal("testv1", cli.BRPop(new[] { "TestBLPop1", "TestBLPop2" }, 5)?.value);

            new Thread(() =>
            {
                Thread.CurrentThread.Join(500);
                cli.RPush("TestBLPop2", "testv2");
            }).Start();
            replacedert.Equal("testv2", cli.BRPop(new[] { "TestBLPop1", "TestBLPop2" }, 5)?.value);
        }

19 View Source File : ListsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void BRPop()
        {
            replacedert.Null(cli.BRPop(new[] { "TestBRPop1", "TestBRPop2" }, 1));

            new Thread(() =>
            {
                Thread.CurrentThread.Join(500);
                cli.LPush("TestBRPop1", "testv1");
            }).Start();
            replacedert.Equal("testv1", cli.BRPop(new[] { "TestBRPop1", "TestBRPop2" }, 5)?.value);

            new Thread(() =>
            {
                cli.LPush("TestBRPop2", "testv2");
            }).Start();
            replacedert.Equal("testv2", cli.BRPop(new[] { "TestBRPop1", "TestBRPop2" }, 5)?.value);
        }

19 View Source File : PubSubTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void Subscribe()
        {
            var key1 = "Subscribe1";
            var key2 = "Subscribe2";

            bool isbreak = false;
            new Thread(() =>
            {
                while (isbreak == false)
                {
                    cli.Publish(key1, Guid.NewGuid().ToString());
                    cli.Publish(key2, Guid.NewGuid().ToString());
                    cli.Publish("randomSubscribe1", Guid.NewGuid().ToString());
                    Thread.CurrentThread.Join(100);
                }
            }).Start();

            using (cli.Subscribe(key1, ondata))
            {
                using (cli.Subscribe(key2, ondata))
                {
                    using (cli.PSubscribe("*", ondata))
                    {
                        Thread.CurrentThread.Join(2000);
                    }
                    Thread.CurrentThread.Join(2000);
                }
                Thread.CurrentThread.Join(2000);
            }
            Trace.WriteLine("one more time");
            using (cli.Subscribe(key1, ondata))
            {
                using (cli.Subscribe(key2, ondata))
                {
                    using (cli.PSubscribe("*", ondata))
                    {
                        Thread.CurrentThread.Join(2000);
                    }
                    Thread.CurrentThread.Join(2000);
                }
                Thread.CurrentThread.Join(2000);
            }
            void ondata(string channel, object data)
            {
                Trace.WriteLine($"{channel} -> {data}");
            }
            isbreak = true;
        }

19 View Source File : ProduceConsumeBufferTest.cs
License : MIT License
Project Creator : 39M

[Test]
    [Timeout(1000)]
    public void Test() {
      Thread consumer = new Thread(new ThreadStart(consumerThread));
      Thread producer = new Thread(new ThreadStart(producerThread));

      consumer.Start();
      producer.Start();

      consumer.Join();
      producer.Join();
    }

19 View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension

public void Connect()
        {
            if (Connected)
                throw new Exception("Can't Connect: Already Connected");

            switch (Properties.Settings.Default.ConnectionType)
            {
                case ConnectionType.Serial:
                    SerialPort port = new SerialPort(Properties.Settings.Default.SerialPortName, Properties.Settings.Default.SerialPortBaud);
                    port.DtrEnable = Properties.Settings.Default.SerialPortDTR;
                    port.Open();
                    Connection = port.BaseStream;
                    break;
                default:
                    throw new Exception("Invalid Connection Type");
            }

            if (Properties.Settings.Default.LogTraffic)
            {
                try
                {
                    Log = new StreamWriter(Constants.LogFile);
                }
                catch (Exception e)
                {
                    NonFatalException("could not open logfile: " + e.Message);
                }
            }

            Connected = true;

            ToSend.Clear();
            ToSendPriority.Clear();
            Sent.Clear();
            ToSendMacro.Clear();

            Mode = OperatingMode.Manual;

            if (PositionUpdateReceived != null)
                PositionUpdateReceived.Invoke();

            WorkerThread = new Thread(Work);
            WorkerThread.Priority = ThreadPriority.AboveNormal;
            WorkerThread.Start();
        }

19 View Source File : SimpleHTTPServer.cs
License : GNU General Public License v3.0
Project Creator : 44670

private void Initialize(int port)
    {
        this._port = port;
        _serverThread = new Thread(this.Listen);
        _serverThread.Start();
    }

19 View Source File : Job.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static void StartLongNew(WaitCallback waitCallback, Token token = null)
        {
            Thread thread = null;
            thread = new Thread(state => {
                if (null != waitCallback)
                {
                    JobState jobState = new JobState();
                    jobState.Token = token ?? new Token();
                    jobState.State = thread;
                    waitCallback.Invoke(jobState);
                }
            });
            thread.Start();
        }

19 View Source File : Job.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static void StartLongNew(WaitCallback waitCallback, DoneSyncCallback doneSyncCallback, Token token = null)
        {
            Thread thread = null;
            thread = new Thread(state => {
                if (null != waitCallback)
                {
                    JobState jobState = new JobState();
                    jobState.Token = token ?? new Token();
                    jobState.State = thread;
                    waitCallback.Invoke(jobState);
                    EnSyncStateQueue(jobState, doneSyncCallback);
                }
            });
            thread.Start();

        }

19 View Source File : LoaderIntegrityCheck.cs
License : GNU General Public License v3.0
Project Creator : 9E4ECDDE

private static void PrintWarnMsg()
        {
            MelonLogger.Error("===================================================================");
            MelonLogger.Error("You're using MelonLoader with important security features missing.");
            MelonLogger.Error("This exposes you to additional risks from certain malicious actors,");
            MelonLogger.Error("including account theft, account bans, and other unwanted consequences");
            MelonLogger.Error("If this is not what you want, download the official installer from");
            MelonLogger.Error("https://github.com/LavaGang/MelonLoader/releases");
            MelonLogger.Error("then close this console, and reinstall MelonLoader using it.");
            MelonLogger.Error("If you want to accept those risks, press Enter to continue");
            MelonLogger.Error("===================================================================");
            //Modified below this point
            new Thread(new ThreadStart(PopupMsg)).Start();
        }

19 View Source File : RtmpServer.cs
License : MIT License
Project Creator : a1q123456

public Task StartAsync(CancellationToken ct = default)
        {
            if (Started)
            {
                throw new InvalidOperationException("already started");
            }
            _webSocketServer?.Start(c =>
            {
                var session = new WebSocketSession(c, _webSocketOptions);
                c.OnOpen = session.HandleOpen;
                c.OnClose = session.HandleClose;
                c.OnMessage = session.HandleMessage;
            });

            if (_webSocketServer != null)
            {
                CancellationTokenRegistration reg = default;
                reg = ct.Register(() =>
                {
                    reg.Dispose();
                    _webSocketServer.Dispose();
                    _webSocketServer = new WebSocketServer(_webSocketOptions.BindEndPoint.ToString());
                });
            }
            Started = true;
            var ret = new TaskCompletionSource<int>();
            var t = new Thread(o =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        try
                        {
                            _allDone.Reset();
                            _listener.BeginAccept(new AsyncCallback(ar =>
                            {
                                AcceptCallback(ar, ct);
                            }), _listener);
                            while (!_allDone.WaitOne(1))
                            {
                                ct.ThrowIfCancellationRequested();
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }
                }
                catch (OperationCanceledException) { }
                finally
                {
                    ret.SetResult(1);
                }
            });

            t.Start();
            return ret.Task;
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestParalleWriteAndRead()
        {
            var random = new Random();
            var buffer = new ByteBuffer(512, 35767);
            var th1 = new Thread(() =>
            {
                byte i = 0;
                while (true)
                {
                    var arr = new byte[new Random().Next(256, 512)];
                    for (var j = 0; j < arr.Length; j++)
                    {
                        arr[j] = i;
                        i++;

                        if (i > 100)
                        {
                            i = 0;
                        }
                    }
                    buffer.WriteToBuffer(arr);
                }
            });
            th1.IsBackground = true;
            th1.Start();

            var th2 = new Thread(() =>
            {
                while (true)
                {
                    var arr = new byte[new Random().Next(129, 136)];
                    if (buffer.Length >= arr.Length)
                    {
                        buffer.TakeOutMemory(arr);

                        for (int i = 1; i < arr.Length; i++)
                        {
                            replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
                        }
                    }
                }
            });
            th2.IsBackground = true;
            th2.Start();

            Thread.Sleep(TimeSpan.FromSeconds(30));

        }

19 View Source File : SettingsManager.cs
License : MIT License
Project Creator : a1xd

public void ResetDriver()
        {
            ActiveConfig = DriverConfig.GetDefault();
            new Thread(() => DriverConfig.Deactivate()).Start();
        }

19 View Source File : SettingsManager.cs
License : MIT License
Project Creator : a1xd

public bool TryActivate(DriverConfig settings, out string errors)
        {
            errors = settings.Errors();

            if (errors == null)
            {
                GuiSettings = MakeGUISettingsFromFields();
                GuiSettings.Save();

                UserConfig = settings;
                ActiveConfig = settings;
                File.WriteAllText(Constants.DefaultSettingsFileName, settings.ToJSON());

                new Thread(() => ActiveConfig.Activate()).Start();
            }

            return errors == null;
        }

19 View Source File : UI.cs
License : MIT License
Project Creator : aaaddress1

private void compile_Click(object sender, EventArgs e)
        {

            (new System.Threading.Thread(() =>
            {
                this.Invoke((MethodInvoker)delegate () {
                    compile.Enabled = false;
                    logBox.Clear();
                    logMsg(demostr, Color.Blue);
                    this.splitContainer.Panel2Collapsed = false;
                    this.logPanelBtn.Text = "x";
                });
                File.WriteAllText(srcPath, this.fastColoredTextBox.Text);
                File.Delete(exePath);
                File.Delete(asmPath);
                File.Delete(obfAsmPath);

                logMsg(" --- \n", Color.Blue);
                logMsg(string.Format(
                        "[\tInfo\t] current compile info... \n" +
                        " - source: {0}\n" +
                        " - asm path: {1}\n" +
                        " - obfuscated asm path: {2}\n" +
                        " - output exe path: {3}\n", srcPath, asmPath, obfAsmPath, exePath), Color.Blue);

                if (compiler.geneateAsmSource(srcPath, asmPath))
                    logMsg("[\tOK\t] generate replacedembly code of source code.", Color.Green);
                else
                {
                    logMsg("[\tFail\t] generate replacedembly code of sorce code failure ...", Color.Red);
                    this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
                    return;
                }

                if (obfuscator.obfuscaAsm(asmPath, obfAsmPath))
                    logMsg("[\tOK\t] generate obfuscated replacedembly code of source code.", Color.Green);
                else
                {
                    logMsg("[\tFail\t] generate obfuscated replacedembly code of sorce code failure ...", Color.Red);
                    this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
                    return;
                }
                if (compiler.generateExe(obfAsmPath, exePath))
                {
                    var arr = System.IO.File.ReadAllBytes(exePath);
                    var size = arr.Length;
                    var md5 = BitConverter.ToString(MD5.Create().ComputeHash(arr)).Replace("-", "");
                    var sha256 = BitConverter.ToString(SHA256.Create().ComputeHash(arr)).Replace("-", "");
                    logMsg("[\tInfo\t] exe size: " + size + " bytes", Color.Blue);
                    logMsg("[\tInfo\t] MD5: " + md5, Color.Blue);
                    logMsg("[\tInfo\t] SHA256: " + sha256, Color.Blue);
                    logMsg("[\tOK\t] generate executable file successfully :)", Color.Green);
                }
                else
                    logMsg("[\tFail\t] generate executable file failure ... o___O", Color.Red);
 
                if (Properties.Settings.Default.clnAftCompile)
                {
                    File.Delete(asmPath);
                    File.Delete(obfAsmPath);
                }
                this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
            })
            { IsBackground = true }).Start();
        }

19 View Source File : WaitMessage.cs
License : MIT License
Project Creator : aabiryukov

public void Show()
		{
			if (m_thread == null)
			{
				m_thread = new Thread(FormThreadMethod)
				          	{
								Name = "WaitMessage Thread", 
								IsBackground = Thread.CurrentThread.IsBackground
				          	};
				m_thread.Start();
			}
		}

19 View Source File : ConnectSaver.cs
License : Apache License 2.0
Project Creator : AantCoder

private static void StartWorker()
        {
            if (Worker != null) return;
            Worker = new Thread(WorkerDo);
            Worker.IsBackground = true;
            Worker.Start();
        }

19 View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : AantCoder

private void ConnectionAccepted(ConnectClient client)
        {
            if (ActiveClientCount > MaxActiveClientCount)
            {
                client.Dispose();
                return;
            }

            Interlocked.Increment(ref _ActiveClientCount);
            var thread = new Thread(() => DoClient(client));
            thread.IsBackground = true;
            thread.Start();
        }

See More Examples