System.Threading.Thread.Join()

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

1042 Examples 7

19 Source : WaveServer.cs
with MIT License
from azist

protected override void DoWaitForCompleteStop()
      {
        s_Servers.Unregister(this);

        if (m_AcceptThread!=null)
        {
          m_AcceptThread.Join();
          m_AcceptThread = null;
        }

        if (m_InstrumentationThread!=null)
        {
          m_InstrumentationThread.Join();
          m_InstrumentationThread = null;
          m_InstrumentationThreadWaiter.Close();
        }

        closeListener();

        try
        {
           m_Dispatcher.WaitForCompleteStop();
           if (m_Gate!=null)
             if (m_Gate is Daemon)
                ((Daemon)m_Gate).WaitForCompleteStop();
        }
        finally
        {
          m_AcceptSemapreplaced.Dispose();
          m_AcceptSemapreplaced = null;

          m_WorkSemapreplaced.Dispose();
          m_WorkSemapreplaced = null;
        }
      }

19 Source : MessageDaemon.cs
with MIT License
from azist

protected override void DoStart()
    {
      WriteLog(MessageType.Trace, nameof(DoStart), "Entering");

      try
      {
        if (m_Sink == null)
          throw new WebException(StringConsts.MAILER_SINK_IS_NOT_SET_ERROR);

        m_Trigger = new AutoResetEvent(false);

        m_Queues = new ConcurrentQueue<Message>[(int)MsgPriority.Slowest + 1];
        for (var i = 0; i < m_Queues.Length; i++)
          m_Queues[i] = new ConcurrentQueue<Message>();

        m_Sink.Start();
        m_FallbackSink.Start();

        m_Thread = new Thread(threadSpin);
        m_Thread.Name = THREAD_NAME;
        m_Thread.IsBackground = false;

        m_Thread.Start();
      }
      catch (Exception error)
      {
        AbortStart();

        if (m_Thread != null)
        {
          m_Thread.Join();
          m_Thread = null;
        }

        WriteLog(MessageType.CatastrophicError, nameof(DoStart), "Leaked: " + error.ToMessageWithType(), error);
        throw error;
      }

      WriteLog(MessageType.Trace, nameof(DoStart), "Exiting");
    }

19 Source : MessageDaemon.cs
with MIT License
from azist

protected override void DoWaitForCompleteStop()
    {
      WriteLog(MessageType.Trace, nameof(DoWaitForCompleteStop), "Entering");

      try
      {
        base.DoWaitForCompleteStop();

        m_Thread.Join();
        m_Thread = null;

        m_Sink.WaitForCompleteStop();
        m_FallbackSink.WaitForCompleteStop();
        m_Trigger.Dispose();
        m_Trigger = null;
      }
      catch (Exception error)
      {
        WriteLog(MessageType.CatastrophicError, nameof(DoWaitForCompleteStop), "Leaked: " + error.ToMessageWithType(), error);
        throw error;
      }

      WriteLog(MessageType.Trace, nameof(DoWaitForCompleteStop), "Exiting");
    }

19 Source : GlueSpeed.cs
with MIT License
from azist

public static void EchoThreaded(IGlue glue, string node, int count, int parallel)
      {
        var tcount = count / parallel;

        var latch = 0;

        var threads = new Thread[parallel];
        for(var i=0; i < threads.Length; i++)
          threads[i] = new Thread( () =>
          {
            var client = new JokeContractClient(glue, node);
            client.ReserveTransport = true;
            client.UnsecureEcho("aaa");

            while(Thread.VolatileRead(ref latch)==0);  //could have used Barrier clreplaced
            for(var j=0; j<tcount; j++)
              client.UnsecEchoMar("aaa");
              //client.Notify(null);

            client.Dispose();
          });

        foreach(var t in threads) t.Start();

        Thread.Sleep(2000);

        var sw = System.Diagnostics.Stopwatch.StartNew();
        Thread.VolatileWrite(ref latch, 1);


        foreach(var t in threads) t.Join();

        Console.WriteLine("Called Unsecure Echo {0} at {1:n0} ops/sec".Args(count, count / (sw.ElapsedMilliseconds / 1000d)));
      }

19 Source : PushHandler.cs
with MIT License
from azist

protected override void Destructor()
    {
      base.Destructor();
      m_Thread.Join();

      foreach(var w in m_Works)
       w.Dispose();
    }

19 Source : AsyncFlowTests.cs
with MIT License
from azist

[Run("capture=true")]
    [Run("capture=false")]
    [Run("capture=true")]
    [Run("capture=false")]
    public void AsyncFlowMutableParallelThreads(bool capture)
    {
      var list = new List<Thread>();
      for(var i=0; i<System.Environment.ProcessorCount * 2; i++)
      {
        var t = new Thread(threadBody);
        t.IsBackground = false;
        list.Add(t);
        t.Start(capture);
      }

      m_Signal = true;

      list.ForEach(t => t.Join());
    }

19 Source : Program.cs
with MIT License
from AzureIoTGBB

static void Main(string[] args)
        {
            Thread readThread = new Thread(Read);

            InitDeviceClient().Wait();

            _serialPort = new SerialPort();

                    // Allow the user to set the appropriate properties.
            _serialPort.PortName = PortName;
            _serialPort.BaudRate = 9600;
            _serialPort.Parity = Parity.None;
            _serialPort.DataBits = 8;
            _serialPort.StopBits = StopBits.One;
            _serialPort.Handshake = Handshake.None;

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            Console.WriteLine($"Serial port [{PortName}] opened");

            _continue = true;
            readThread.Start();

            Console.WriteLine("press <enter> to exit");

            Console.ReadLine();

            _continue = false;

            readThread.Join();
            _serialPort.Close();
            //_deviceClient.Close();

        }

19 Source : Program.cs
with MIT License
from AzureIoTGBB

static void Main(string[] args)
        {
            Thread readThread = new Thread(Read);

            InitDeviceClient().Wait();

            _continue = true;
            readThread.Start();

            Console.WriteLine("press <enter> to exit");
            Console.ReadLine();

            _continue = false;

            readThread.Join();

        }

19 Source : MemoryModelDeadlock.cs
with MIT License
from badamczewski

public void SpinLockTest()
        {
            Thread[] threads = new Thread[32];
            for(int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(() => Spin());
            }

            for (int i = 0; i < threads.Length; i++)
            {
                threads[i].Start();
            }

            for (int i = 0; i < threads.Length; i++)
            {
                threads[i].Join();
            }

            Console.WriteLine("[Done]");
        }

19 Source : EventTests.cs
with MIT License
from backtrace-labs

[TestCase(1)]
        [TestCase(5)]
        [TestCase(10)]
        [Test(Author = "Konrad Dysput", Description = "Test OnReportStart, BeforeSend and AfterSend events")]
        public void TestStartAndStopEvents(int numberOfThreads)
        {
            //setup test method
            //Test case tests Send and SendAsync method - magic number 2 means that we test 2 methods
            var expectedNumberOfStarts = numberOfThreads * 2;
            var expectedNumberOfEnds = numberOfThreads * 2;
            var expectedNumberOfBeforeSendEvents = numberOfThreads * 2;

            var threads = new List<Thread>();
            int totalStart = 0;
            int totalBeforeSend = 0;
            int totalEnds = 0;

            _backtraceClient.OnReportStart = (BacktraceReport report) =>
            {
                Interlocked.Increment(ref totalStart);
            };

            _backtraceClient.BeforeSend = (BacktraceData data) =>
            {
                Interlocked.Increment(ref totalBeforeSend);
                return data;
            };

            _backtraceClient.AfterSend = (BacktraceResult result) =>
            {
                Interlocked.Increment(ref totalEnds);
            };

            for (int threadIndex = 0; threadIndex < numberOfThreads; threadIndex++)
            {

                threads.Add(new Thread(new ThreadStart(() =>
                {
                    _backtraceClient.Send("client message");
                    Task.WaitAll(_backtraceClient.SendAsync("client message"));
                })));
            }

            threads.ForEach(n => n.Start());
            threads.ForEach(n => n.Join());

            replacedert.AreEqual(expectedNumberOfStarts, totalStart);
            replacedert.AreEqual(expectedNumberOfBeforeSendEvents, totalBeforeSend);
            replacedert.AreEqual(expectedNumberOfEnds, totalEnds);
        }

19 Source : TestUtils.cs
with MIT License
from Bannerlord-Coop-Team

private void stopMainLoop()
            {
                if (m_Thread == null)
                {
                    return;
                }

                lock (m_StopRequestLock)
                {
                    m_bStopRequest = true;
                }

                m_Thread.Join();
                m_Thread = null;
            }

19 Source : DiscoveryThread.cs
with MIT License
from Bannerlord-Coop-Team

private void Stop()
        {
            if (m_Thread == null)
            {
                return;
            }

            lock (m_StopRequestLock)
            {
                m_IsStopRequest = false;
            }

            m_Thread.Join();
            m_Thread = null;
        }

19 Source : Server.cs
with MIT License
from Bannerlord-Coop-Team

private void StopMainLoop()
        {
            if (m_Thread == null)
            {
                return;
            }

            lock (m_StopRequestLock)
            {
                m_IsStopRequest = true;
            }

            m_Thread.Join();
            m_Thread = null;
        }

19 Source : ManagedThreadAlphaSynthWorkerApi.cs
with GNU General Public License v3.0
from BardMusicPlayer

public override void Destroy()
        {
            _workerCancellationToken.Cancel();
            _workerThread.Join();
        }

19 Source : ExecutorThread.cs
with GNU General Public License v3.0
from BastianBlokland

public void Dispose()
        {
            //Request cancellation
            cancelTokenSource.Cancel();

            //Wait for the executor thread to cancel itself
            thread.Join();

            //Dispose resources
            cancelTokenSource.Dispose();
            wakeEvent.Dispose();
        }

19 Source : BigBlueButtonFacade.cs
with MIT License
from berkayalcin

public async Task StartAsync()
        {
            if (!_isDownloadWebcamVideo && !_isDownloadPresentation)
                throw new Exception("Either Presentaton or Desk-share Video Must Be Selected");

            if (!Directory.Exists(_outputDirectory))
                Directory.CreateDirectory(_outputDirectory);

            Directory.SetCurrentDirectory(_outputDirectory);

            bool downloadVideoResponse = false,
                downloadPresentationResponse = false,
                hasAudio = false;

            _webDriver = WebDriverFactory.Create(_webDriverType, _url);


            _bigBlueButtonDoreplacedentParser = new BigBlueButtonDoreplacedentParser(_webDriver, Options);

            var deskShareVideoName = $"{_outputFileName}-desk";
            var webcamVideoName = $"{_outputFileName}-webcam";
            var audioOutputName = $"{_outputFileName}-output";
            var presentationName = $"{_outputFileName}-presentation";
            var tmpPresentationName = $"{_outputFileName}-tmp";

            var downloadDeskShareThread = new Thread(() =>
            {
                if (_isDownloadDeskShareVideo)
                {
                    var response = DownloadVideo(deskShareVideoName).GetAwaiter().GetResult();
                    downloadVideoResponse = response.IsSuccess;
                }
            });

            var downloadWebcamThread = new Thread(() =>
            {
                if (_isDownloadWebcamVideo)
                {
                    var response = DownloadWebcam(webcamVideoName).GetAwaiter().GetResult();
                    hasAudio = response.IsSuccess;
                }
            });

            var downloadPresentationThread = new Thread(() =>
            {
                if (_isDownloadPresentation)
                {
                    var response = DownloadPresentation(tmpPresentationName).GetAwaiter().GetResult();
                    downloadPresentationResponse = response.IsSuccess;
                }
            });


            downloadDeskShareThread.Start();
            downloadWebcamThread.Start();
            downloadPresentationThread.Start();

            downloadWebcamThread.Join();
            downloadDeskShareThread.Join();
            downloadPresentationThread.Join();


            if (!downloadVideoResponse && !downloadPresentationResponse)
                throw new BigBlueButtonDoreplacedentException("Neither Video Nor Presentation Couldn't Be Downloaded.");


            var audioInputPath = AppDomainHelpers.GetPath(_outputDirectory, webcamVideoName, ".mp4");
            var audioOutputPath = AppDomainHelpers.GetPath(_outputDirectory, $"{audioOutputName}", ".mp3");
            var deskShareInputPath = AppDomainHelpers.GetPath(_outputDirectory, $"{deskShareVideoName}", ".mp4");
            var videoOutputPath = AppDomainHelpers.GetPath(_outputDirectory, _outputFileName, ".mp4");
            var presentationOutputPath = AppDomainHelpers.GetPath(_outputDirectory, presentationName, ".mp4");
            var tmpPresentationPath = AppDomainHelpers.GetPath(_outputDirectory, tmpPresentationName, ".mp4");
            if (downloadVideoResponse)
            {
                if (hasAudio)
                    await _videoService.ExtractAndAddAudio(audioInputPath, audioOutputPath, deskShareInputPath,
                        videoOutputPath, _outputDirectory, _isUseMulreplacedhread, true);
                else
                    File.Move(deskShareInputPath, videoOutputPath, true);
            }

            if (downloadPresentationResponse)
            {
                if (hasAudio)
                    await _videoService.ExtractAndAddAudio(audioInputPath, audioOutputPath, tmpPresentationPath,
                        presentationOutputPath, _outputDirectory, _isUseMulreplacedhread, true);
                else
                    File.Move(tmpPresentationPath, presentationOutputPath, true);
            }


            RemoveTempFiles(
                audioOutputName,
                deskShareVideoName,
                tmpPresentationName
            );
            _webDriver.Quit();
        }

19 Source : EnqueueInBackgroundProcessor.cs
with MIT License
from bibigone

public override void Dispose()
        {
            if (processing)
            {
                processing = false;
                if (backgroundThread.ThreadState != ThreadState.Unstarted)
                    backgroundThread.Join();
            }

            base.Dispose();
        }

19 Source : BackgroundReadingLoop.cs
with MIT License
from bibigone

public virtual void Dispose()
        {
            if (isRunning)
            {
                isRunning = false;
                if (backgroundThread.ThreadState != System.Threading.ThreadState.Unstarted)
                    backgroundThread.Join();
            }
        }

19 Source : Processor.cs
with MIT License
from bibigone

public void Stop()
        {
            lock (sync)
            {
                if (thread != null)
                {
                    cancellation.Cancel();
                    try
                    {
                        thread.Join();
                    }
                    catch (ThreadStateException) { }
                    catch (ThreadInterruptedException) { }

                    lock (queue)
                    {
                        ClearQueue();
                    }

                    cancellation.Dispose();
                    thread = null;
                }
            }
        }

19 Source : BackgroundTrackingLoop.cs
with MIT License
from bibigone

public void Dispose()
        {
            if (isRunning)
            {
                isRunning = false;
                if (backgroundThread.ThreadState != ThreadState.Unstarted)
                    backgroundThread.Join();
            }

            tracker.Dispose();
        }

19 Source : Server.cs
with GNU General Public License v3.0
from BigETI

public void FetchMultiData(ERequestResponseType[] requestTypes)
        {
            Dictionary<ERequestResponseType, Thread> ts = new Dictionary<ERequestResponseType, Thread>();
            foreach (ERequestResponseType rt in requestTypes)
            {
                if (!(ts.ContainsKey(rt)))
                {
                    AbortThread(rt);
                    requestsRequired[rt] = true;
                    Thread t = new Thread(() => SendQuery(rt));
                    threads[(int)rt] = t;
                    ts.Add(rt, t);
                    try
                    {
                        t.Start();
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                    }
                }
            }
            foreach (Thread t in ts.Values)
            {
                t.Join();
            }
        }

19 Source : Server.cs
with GNU General Public License v3.0
from BigETI

private void JoinAllThreads()
        {
            foreach (Thread t in threads)
            {
                if (t != null)
                {
                    try
                    {
                        t.Join();
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                    }
                }
            }
        }

19 Source : AudioPlayer.cs
with MIT License
from BleuBleu

public override void Shutdown()
        {
            stopEvent.Set();
            if (playerThread != null)
                playerThread.Join();

            audioStream.Dispose();
        }

19 Source : WinApiHookManager.cs
with MIT License
from blish-hud

public void DisableHook() {
            if ((thread == null) || stopRequested) return;

            Logger.Debug("Disabling WinAPI input hooks");

            mouseHookManager.DisableHook();
            keyboardHookManager.DisableHook();

            stopRequested = true;
            thread.Join();

            stopRequested = false;
            thread        = null;
        }

19 Source : Physics.cs
with BSD 3-Clause "New" or "Revised" License
from bmdub

public void Dispose()
			{
				if (!disposed)
				{
					disposed = true;
					SignalThreads();
					for (int i = 0; i < bufferPools.Length; ++i)
					{
						bufferPools[i].Clear();
					}
					foreach (var worker in workers)
					{
						worker.Thread.Join();
						worker.Signal.Dispose();
					}
				}
			}

19 Source : CodeLab.cs
with MIT License
from BoltBait

protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
        {
            CodeLabConfigToken sect = (CodeLabConfigToken)parameters;
            userEffect = sect.UserScriptObject;
            projectType = sect.ProjectType;

            if (projectType == ProjectType.Shape)
            {
                Size srcSize = EnvironmentParameters.SourceSurface.Size;
                Rectangle selection = EnvironmentParameters.SelectionBounds;
                ColorBgra strokeColor = EnvironmentParameters.PrimaryColor;
                ColorBgra fillColor = EnvironmentParameters.SecondaryColor;
                double strokeThickness = EnvironmentParameters.BrushWidth;

                Thread t = new Thread(() =>
                {
                    ShapeBuilder.SetEnviromentParams(srcSize.Width, srcSize.Height, selection.X, selection.Y, selection.Width, selection.Height, strokeColor, fillColor, strokeThickness);
                    ShapeBuilder.RenderShape(sect.UserCode);
                });
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
                t.Join();

                shapeSurface?.Dispose();
                shapeSurface = (ShapeBuilder.Shape != null) ?
                    Surface.CopyFromBitmap(ShapeBuilder.Shape) :
                    null;
            }
            else if (projectType == ProjectType.Effect && userEffect != null)
            {
                userEffect.EnvironmentParameters = this.EnvironmentParameters;

                try
                {
                    userEffect.SetRenderInfo(sect.PreviewToken, dstArgs, srcArgs);
                    fetchDebugMsg = true;
                }
                catch (Exception exc)
                {
                    sect.LastExceptions.Add(exc);
                    dstArgs.Surface.CopySurface(srcArgs.Surface);
                    sect.UserScriptObject = null;
                    userEffect?.Dispose();
                    userEffect = null;
                }
            }

            base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
        }

19 Source : ObservableCombinators.cs
with MIT License
from bonsai-rx

[Obsolete]
        public static IObservable<TSource> GenerateWithThread<TSource>(Action<IObserver<TSource>> generator)
        {
            return Observable.Create<TSource>(observer =>
            {
                var running = true;
                var thread = new Thread(() =>
                {
                    while (running)
                    {
                        generator(observer);
                    }
                });

                thread.Start();
                return () =>
                {
                    running = false;
                    if (thread != Thread.CurrentThread) thread.Join();
                };
            });
        }

19 Source : Member.cs
with GNU General Public License v3.0
from bosima

public void Close()
        {
            _managerElectionWatchThreadCts.Cancel();
            if (_managerElectionWatchThread != null)
            {
                try
                {
                    _managerElectionWatchThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("等待Manager选举线程退出时发生异常", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("清理Manager选举线程完毕");

            if (_manager != null)
            {
                _manager.Stop();
                _manager = null;
            }

            if (_worker != null)
            {
                _worker.Stop();
                _worker = null;
            }

            StopCommunicator();
        }

19 Source : Worker.cs
with GNU General Public License v3.0
from bosima

public void Stop()
        {
            LogWriter.Write("worker play stopping ...");

            _cluster.StopMonitorJobConfigsFromConfigCenter();

            _jobProcessThreadCts.Cancel();
            if (_jobProcessThread != null)
            {
                try
                {
                    _jobProcessThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("wait for job process thread exit go exception", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("job process thread has exited");

            _cleanExitedSystemTaskThreadCts.Cancel();
            if (_cleanExitedSystemTaskThread != null)
            {
                try
                {
                    _cleanExitedSystemTaskThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("wait for clean system task thread exit go exception", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("clean system task thread has exited");

            _cleanOutOfControlChildProcessThreadCts.Cancel();
            if (_cleanOutOfControlChildProcessThread != null)
            {
                try
                {
                    _cleanOutOfControlChildProcessThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("wait for clean out of control process thread exit go exception", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("clean out of control process thread has exited");

            // 经过上边的处理,应该不会有未处理的进程了
            // KillChildProcess();

            LogWriter.Write("worker play stopped");
        }

19 Source : Manager.cs
with GNU General Public License v3.0
from bosima

public void Stop()
        {
            LogWriter.Write("manager play stopping ...");

            _cluster.StopMonitorJobCreate();
            _cluster.StopMonitorJobConfigsFromDisk();
            _cluster.StopMonitorJobConfigsFromConfigCenter();
            _cluster.StopMonitorMemberHealth();

            _jobProcessThreadCts.Cancel();
            if (_jobProcessThread != null)
            {
                try
                {
                    _jobProcessThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("wait for job process thread exit go exception", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("clean job process thread has exited");

            _cleanExitedSystemTaskThreadCts.Cancel();
            if (_cleanExitedSystemTaskThread != null)
            {
                try
                {
                    _cleanExitedSystemTaskThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("wait for clean system task thread exit go exception", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("clean system task thread has exited");

            _cleanOutOfControlChildProcessThreadCts.Cancel();
            if (_cleanOutOfControlChildProcessThread != null)
            {
                try
                {
                    _cleanOutOfControlChildProcessThread.Join();
                }
                catch (Exception ex)
                {
                    LogWriter.Write("wait for clean out of control process thread exit go exception", ex, LogLevel.Warn);
                }
            }
            LogWriter.Write("clean out of control process thread has exited");

            // 经过上边的处理,应该不会有未处理的进程了,
            // 除非Stop的过程中程序退出了,但是剧本上线的时候还会继续检查不受控制的进程
            // KillChildProcess();

            LogWriter.Write("manager play stopped");
        }

19 Source : Program.cs
with GNU General Public License v3.0
from bp2008

static void Main()
		{
			string exePath = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
			Globals.Initialize(exePath);
			PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "BiUpdateHelper_Log.txt");

			FileInfo fiExe = new FileInfo(exePath);
			Environment.CurrentDirectory = fiExe.Directory.FullName;

			settings = new BiUpdateHelperSettings();
			settings.Load();
			if (string.IsNullOrWhiteSpace(settings.secret))
			{
				settings.secret = Hash.GetSHA256Hex(Guid.NewGuid().ToString());
				settings.Save();
			}
			settings.SaveIfNoExist();

			RegistryUtil.Force32BitRegistryAccess = settings.bi32OnWin64;

			AutoFixBad32BitSetting();

			PerformanceData.PerformanceDataCollector.onReportUploaded = () =>
			{
				settings.Load();
				settings.lastUsageReportAt = TimeUtil.GetTimeInMsSinceEpoch();
				settings.Save();
			};
			PerformanceData.PerformanceDataCollector.getSecretString = () =>
			{
				return Program.settings.secret;
			};

			if (Environment.UserInteractive)
			{
				string replacedle = "BiUpdateHelper " + System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + " Service Manager";
				string ServiceName = "BiUpdateHelper";
				ButtonDefinition btnRegKey = new ButtonDefinition("BI Registration Info", btnRegkey_Click);
				ButtonDefinition btnSettings = new ButtonDefinition("Edit Service Settings", btnSettings_Click);
				ButtonDefinition btnCameraConfigLinks = new ButtonDefinition("Camera Config Links", btnCameraConfigLinks_Click);
				ButtonDefinition btnRegistryBackupNow = new ButtonDefinition("Take Registry Backup Now", btnRegistryBackupNow_Click);
				ButtonDefinition btnPerfData = new ButtonDefinition("Performance Data", btnPerfData_Click);
				ButtonDefinition[] customButtons = new ButtonDefinition[] { btnRegKey, btnSettings, btnCameraConfigLinks, btnRegistryBackupNow, btnPerfData };

				Thread thrGUI = new Thread(() =>
				{
					System.Windows.Forms.Application.Run(new ServiceManager(replacedle, ServiceName, customButtons));
				});
				thrGUI.SetApartmentState(ApartmentState.STA);
				thrGUI.Start();
				thrGUI.Join();
			}
			else
			{
				ServiceBase[] ServicesToRun;
				ServicesToRun = new ServiceBase[]
				{
					new MainSvc()
				};
				ServiceBase.Run(ServicesToRun);
			}
		}

19 Source : BaseThread.cs
with MIT License
from breinsp

public void StopAndWait()
        {
            Stop();
            thread.Join();
        }

19 Source : Authenticate.cs
with MIT License
from brianzhouzc

public override string ProvideSecondFactorPreplacedword(SecondFactorMethod method)
            {
                string code = "";
                var thread = new Thread(
                       () =>
                       {
                           Main.form.twofactor = new TwoFactor();
                           var result = Main.form.twofactor.ShowDialog();

                           if (result == DialogResult.OK)
                           {
                               code = Main.form.twofactor.authcode;
                           }
                           else
                           {
                               code = "";
                           }
                       });

                thread.Start();
                thread.Join();
                return code;
            }

19 Source : SerialStream.cs
with GNU General Public License v3.0
from BrianLima

public override void Stop()
        {
            _log.Debug("Stop called.");
            if (_workerThread == null) return;

            _cancellationTokenSource.Cancel();
            _cancellationTokenSource = null;
            _workerThread.Join();
            _workerThread = null;
            running = false;
        }

19 Source : BreathMode.xaml.cs
with GNU General Public License v3.0
from BrianLima

private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource = null;
            _workerThread.Join();
            _workerThread = null;
        }

19 Source : JoystickMode.xaml.cs
with GNU General Public License v3.0
from BrianLima

public void Stop()
        {
            if (_workerThread == null) return;

            _cancellationTokenSource.Cancel();
            _cancellationTokenSource = null;
            _workerThread.Join();
            _workerThread = null;
            running = false;
        }

19 Source : Authenticate.cs
with MIT License
from brianzhouzc

private void loginButton_Click(object sender, EventArgs e)
        {
            if (usernameTextField.Text != "" && preplacedwordTextField.Text != "")
            {
                var id = "060b5cde8c3d11e89eb6529269fb1459";
                var description = "LastPreplaced for Wox";
                try
                {
                    var thread = new Thread(
                       () =>
                       {
                           vault = Vault.Open(usernameTextField.Text,
                                            preplacedwordTextField.Text,
                                            new ClientInfo(Platform.Desktop, id, description, false),
                                            new TwoFactorUI());
                       });

                    thread.Start();
                    thread.Join();

                    if (rememberUsernameCheckBox.Checked)
                        Properties.Settings.Default.username = usernameTextField.Text;
                    else
                        Properties.Settings.Default.username = "";

                    if (rememberPreplacedwordCheckBox.Checked)
                        Properties.Settings.Default.preplacedword = preplacedwordTextField.Text;
                    else
                        Properties.Settings.Default.preplacedword = "";

                    Properties.Settings.Default.saveusername = rememberUsernameCheckBox.Checked;
                    Properties.Settings.Default.savepreplacedword = rememberPreplacedwordCheckBox.Checked;
                    Properties.Settings.Default.Save();

                    
                    Main.form.twofactor.Close();
                    Main.form.twofactor.Dispose();

                    Main.form.Close();
                    Main.form.Dispose();
                    MessageBox.Show("You have successfully logged in.");
                }
                catch (Exception ex)
                {
                    vault = null;
                    MessageBox.Show("Something went wrong, maybe wrong username or preplacedword?", "Error", MessageBoxButtons.OK);
                }

            }
            else
            {
                MessageBox.Show("You are missing some information!", "You are missing some information!", MessageBoxButtons.OK);
            }
        }

19 Source : ClipboardHelper.cs
with MIT License
from C1rdec

private static void RetryOnMainThread(Action action)
        {
            Thread thread = new Thread(() =>
            {
                var retryCount = 3;
                while (retryCount != 0)
                {
                    try
                    {
                        action();
                        break;
                    }
                    catch
                    {
                        retryCount--;
                        Thread.Sleep(200);
                    }
                }
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
        }

19 Source : ComTaskScheduler.cs
with Apache License 2.0
from cairoshell

public void Wait()
        {
            if (this._cancellationToken.IsCancellationRequested)
                throw new TaskSchedulerException("Cannot wait after disposal.");

            this._tasks.CompleteAdding();
            this._thread.Join();

            this._cancellationToken.Cancel();
        }

19 Source : InteractiveBrokersBrokerage.cs
with Apache License 2.0
from Capnode

public override void Disconnect()
        {
            _client?.ClientSocket.eDisconnect();

            if (_messageProcessingThread != null)
            {
                _signal.issueSignal();
                _messageProcessingThread.Join();
                _messageProcessingThread = null;
            }
        }

19 Source : DefaultConnectionHandler.cs
with Apache License 2.0
from Capnode

public void Dispose()
        {
            _isEnabled = false;

            // request and wait for thread to stop
            _cancellationTokenSource?.Cancel();
            _connectionMonitorThread?.Join();
        }

19 Source : TimeIndexTest.cs
with MIT License
from capslocky

[TestMethod]
        public void OneKeyMultipleThreads() 
        {
            const string key = "'beta";
            const int count = 1000;

            var results = new TimeIndex[count];
        
            var threadArray = Enumerable.Range(0, count).Select(index => 
                new Thread(() =>
                {
                    var timeIndex = TimeIndex.GetUnique(key);
                    Trace.WriteLine("Result = " + timeIndex + " Index = " + index.ToString("000") + " ThreadId = " + Thread.CurrentThread.ManagedThreadId);
                    results[index] = timeIndex;
                }
            )).ToArray();


            Array.ForEach(threadArray, thread => thread.Start());
            Array.ForEach(threadArray, thread => thread.Join());

            CheckOneKeyResults(results);
        }

19 Source : KeyboardDispatcher.cs
with MIT License
from ccajas

void EventInput_CharEntered(object sender, EventInput.CharacterEventArgs e)
        {
            if (_subscriber == null)
                return;
            if (char.IsControl(e.Character))
            {
                //ctrl-v
                if (e.Character == 0x16)
                {
                    //XNA runs in Multiple Thread Apartment state, which cannot recieve clipboard
                    Thread thread = new Thread(PasteThread);
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                    _subscriber.RecieveTextInput(_pasteResult);
                }
                else
                {
                    _subscriber.RecieveCommandInput(e.Character);
                }
            }
            else
            {
                _subscriber.RecieveTextInput(e.Character);
            }
        }

19 Source : SpanExporterTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void InterruptWorkerThreadStops()
        {
  
            Thread serviceExporterThread = ((SpanExporter)spanExporter).ServiceExporterThread;
            spanExporter.Dispose();
            // serviceExporterThread.Interrupt();
            // Test that the worker thread will stop.
            serviceExporterThread.Join();
        }

19 Source : IoTests.cs
with GNU General Public License v3.0
from chaincase-app

[Fact]
		public async Task IoTestsAsync()
		{
			var file = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName(), $"file.dat");

			DigestableSafeMutexIoManager ioman = new DigestableSafeMutexIoManager(file);
			ioman.DeleteMe();
			await ioman.WriteAllLinesAsync(Array.Empty<string>());
			replacedert.False(File.Exists(ioman.FilePath));
			IoHelpers.EnsureContainingDirectoryExists(ioman.FilePath);
			File.Create(ioman.FilePath).Dispose();

			static string RandomString()
			{
				StringBuilder builder = new StringBuilder();
				var rnd = new Random();
				char ch;
				for (int i = 0; i < rnd.Next(10, 100); i++)
				{
					ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65)));
					builder.Append(ch);
				}
				return builder.ToString();
			};

			var list = new List<string>();
			async Task WriteNextLineAsync()
			{
				var next = RandomString();
				lock (list)
				{
					list.Add(next);
				}
				using (await ioman.Mutex.LockAsync())
				{
					var lines = (await ioman.ReadAllLinesAsync()).ToList();
					lines.Add(next);
					await ioman.WriteAllLinesAsync(lines);
				}
			};

			const int Iterations = 200;

			var t1 = new Thread(() =>
			{
				for (var i = 0; i < Iterations; i++)
				{
					/* We have to block the Thread.
					 * If we use async/await pattern then Join() function at the end will indicate that the Thread is finished -
					 * which is not true because the WriteNextLineAsync() is not yet finished. The reason is that await will return execution
					 * the to the calling thread it is detected as the thread is done. t1 and t2 and t3 will still run in parallel!
					 */
					WriteNextLineAsync().Wait();
				}
			});
			var t2 = new Thread(() =>
			{
				for (var i = 0; i < Iterations; i++)
				{
					WriteNextLineAsync().Wait();
				}
			});
			var t3 = new Thread(() =>
			{
				for (var i = 0; i < Iterations; i++)
				{
					WriteNextLineAsync().Wait();
				}
			});

			t1.Start();
			t2.Start();
			t3.Start();
			await Task.Delay(100);
			t1.Join();
			t2.Join();
			t3.Join();
			replacedert.False(t1.IsAlive);
			replacedert.False(t2.IsAlive);
			replacedert.False(t3.IsAlive);

			var allLines = File.ReadAllLines(file);
			replacedert.NotEmpty(allLines);

			/* Lines were added to the list and to the file parallel so the two data should be equal.
			 * If we "substract" them from each other we should get empty array.
			 */

			var diff = allLines.Except(list);
			replacedert.Empty(diff);
		}

19 Source : AsyncMutexTests.cs
with GNU General Public License v3.0
from chaincase-app

[Fact]
		public async Task AsyncMutexTestsAsync()
		{
			var mutexName1 = $"mutex1-{DateTime.Now.Ticks}"; // Randomize the name to avoid system wide collisions.

			AsyncMutex asyncMutex = new AsyncMutex(mutexName1);

			// Cannot be IDisposable because the pattern is like Nito's AsyncLock.
			replacedert.False(asyncMutex is IDisposable);

			// Use the mutex two times after each other.
			using (await asyncMutex.LockAsync())
			{
				await Task.Delay(1);
			}

			using (await asyncMutex.LockAsync())
			{
				await Task.Delay(1);
			}

			// Release the Mutex from another thread.

			var disposable = await asyncMutex.LockAsync();

			var myThread = new Thread(new ThreadStart(() => disposable.Dispose()));
			myThread.Start();
			myThread.Join();

			using (await asyncMutex.LockAsync())
			{
				await Task.Delay(1);
			}

			// Standard Mutex test.
			int cnt = 0;
			List<int> numbers = new List<int>();
			var rand = new Random();
			async Task TestLockAsync()
			{
				using (await asyncMutex.LockAsync())
				{
					cnt++;

					await Task.Delay(rand.Next(5));
					numbers.Add(cnt);
				}
			}

			var tasks = new List<Task>();

			for (int i = 0; i < 100; i++)
			{
				var task = TestLockAsync();

				tasks.Add(task);
			}

			await Task.WhenAll(tasks);

			replacedert.Equal(100, numbers.Count);
			for (int i = 1; i < 100; i++)
			{
				var prevnum = numbers[i - 1];
				var num = numbers[i];
				replacedert.Equal(prevnum + 1, num);
			}

			var mutexName2 = $"mutex2-{DateTime.Now.Ticks}";

			// Test that asynclock cancellation is going to throw IOException.
			var mutex = new AsyncMutex(mutexName2);
			using (await mutex.LockAsync())
			{
				using var cts = new CancellationTokenSource(100);
				await replacedert.ThrowsAsync<IOException>(async () =>
					{
						using (await mutex.LockAsync(cts.Token))
						{
						}
					});
			}

			// Test same mutex gets same asynclock.
			var mutex1 = new AsyncMutex(mutexName2);
			using (await mutex1.LockAsync())
			{
				using var cts = new CancellationTokenSource(100);
				var mutex2 = new AsyncMutex(mutexName2);
				await replacedert.ThrowsAsync<IOException>(async () =>
				{
					using (await mutex2.LockAsync(cts.Token))
					{
					}
				});
			}

			// Concurrency test with the same AsyncMutex object.
			await TestMutexConcurrencyAsync(asyncMutex, asyncMutex);

			// Concurrency test with different AsyncMutex object but same name.
			AsyncMutex asyncMutex2 = new AsyncMutex(mutexName1);
			await TestMutexConcurrencyAsync(asyncMutex, asyncMutex2);
		}

19 Source : SupervisorTests.cs
with MIT License
from chebum

[TestMethod]
        public void MonitorProcess() {
            var args = new ProgramArgs {
                ExeName = "cmd.exe"
            };
            var monitor = new MonitorThread(args);
            try {
                // Process won't start until this thread is idle
                var waitForProcess = new Thread(delegate () {
                    for (int i = 0; i < 30; i++) {
                        if (monitor.Process != null)
                            break;
                        else
                            Thread.Sleep((i + 1) * 100);
                    }
                });
                waitForProcess.Start();
                waitForProcess.Join();
                Console.WriteLine("test");
                replacedert.IsNotNull(monitor.Process);
                replacedert.IsFalse(monitor.Process.HasExited);
                
                var process1 = monitor.Process;
                monitor.Process.Kill();
                waitForProcess = new Thread(delegate () {
                    for (int i = 0; i < 30; i++) {
                        if (monitor.Process != process1)
                            break;
                        else
                            Thread.Sleep((i + 1) * 100);
                    }
                });
                waitForProcess.Start();
                waitForProcess.Join();
                replacedert.IsNotNull(monitor.Process);
                
                monitor.Stop();
                monitor.Join();
                replacedert.IsTrue(monitor.Process.HasExited);
            } finally {
                monitor.Stop();
                monitor.Join();
            }
        }

19 Source : Program.cs
with MIT License
from chebum

public void Join() {
            if (Thread.IsAlive)
                Thread.Join();
        }

19 Source : RGBFusionWrapper.cs
with GNU General Public License v3.0
from Cheerpipe

public void Init(bool startListening = true)
        {
            var initThread = new Thread(DoInit);
            initThread.SetApartmentState(ApartmentState.STA);
            initThread.Start();
            initThread.Join();

            if (startListening)
                StartListening();
        }

19 Source : RGBFusionWrapper.cs
with GNU General Public License v3.0
from Cheerpipe

public void StartListening()
        {
            _MainBoardRingCommandsThread = new Thread(SetMainboardRingAreas);
            _MainBoardRingCommandsThread.SetApartmentState(ApartmentState.STA);
            _MainBoardRingCommandsThread.Start();
            _MainBoardRingCommandsThread.Join();
        }

See More Examples