[Test] // bug #325566 public void GetHashCodeTest() { C1Test test1 = new C1Test(); Thread tA = new Thread(new ThreadStart(test1.TestMethod)); int hA1 = tA.GetHashCode(); Assert.IsTrue(hA1 > 0, "#A1"); tA.Start(); int hA2 = tA.GetHashCode(); Assert.AreEqual(hA1, hA2, "#A2"); tA.Join(); int hA3 = tA.GetHashCode(); Assert.AreEqual(hA1, hA3, "#A3"); Assert.AreEqual(hA1, tA.ManagedThreadId, "#A4"); test1 = new C1Test(); Thread tB = new Thread(new ThreadStart(test1.TestMethod)); int hB1 = tB.GetHashCode(); Assert.IsTrue(hB1 > 0, "#B1"); tB.Start(); int hB2 = tB.GetHashCode(); Assert.AreEqual(hB1, hB2, "#B2"); tB.Join(); int hB3 = tB.GetHashCode(); Assert.AreEqual(hB1, hB3, "#B3"); Assert.AreEqual(hB1, tB.ManagedThreadId, "#B4"); Assert.IsFalse(hA2 == hB2, "#B5"); }
void SaveInfo() { Console.WriteLine("Поток " + demoThread.GetHashCode() + " стартанул"); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; writer = XmlWriter.Create(myStream, settings); writer.WriteStartElement("Info"); foreach (Items el in Elements) { writer.WriteStartElement("Item"); writer.WriteElementString("Name", el.Name); writer.WriteElementString("CreationTime", el.CreationTime); writer.WriteElementString("LastWriteTime", el.LastWriteTime); writer.WriteElementString("LastAccessTime", el.LastAccessTime); writer.WriteElementString("Attributes", el.Attributes); writer.WriteElementString("Size", el.Size); writer.WriteElementString("Owner", el.Owner); writer.WriteElementString("Permission", el.Permission); writer.WriteEndElement(); } writer.WriteEndElement(); writer.Close(); myStream.Close(); Console.WriteLine("Поток " + demoThread.GetHashCode() + " погиб"); }
private void _ExcuteLog() { Logger.LogWarning($"开始处理日志线程:{m_logThread.GetHashCode()}"); while (m_logThread.IsAlive) { if (logQueue.Count > 0) { lock (logQueue) { var t = logQueue.Dequeue(); gameLogger.Log(t.packet, t.frame, t.stackTrace); t.Free(); } } else if (m_pending) { m_logThread.Interrupt(); break; } else { Thread.Sleep(10); } } Logger.LogWarning($"结束处理日志线程:{m_logThread.GetHashCode()}"); }
private Task <int> Buy(int sum) { Thread currentThread = Thread.CurrentThread; if (accountAmount == 0) { throw new InvalidOperationException($"Нулевой баланс... {currentThread.GetHashCode()}"); } // Условие никогда не выполнится, пока вы не закомментируете lock. if (accountAmount < 0) { throw new InvalidOperationException($"Отрицательный баланс {currentThread.GetHashCode()}"); } lock (thisLock) { if (accountAmount >= sum) { Console.WriteLine($"Текущий поток: {currentThread.GetHashCode()}"); Console.WriteLine($"Состояние счета: {accountAmount}"); Console.WriteLine($" Покупка на сумму: {sum}"); accountAmount = accountAmount - sum; Console.WriteLine($"Счет после пок.: {accountAmount}"); return(new Task <int>(() => sum)); } else { // Не хватает денег - отказываем в покупке. return(new Task <int>(() => 0)); } } }
public static void Main() { string msg = null; Thread th = new Thread(new ThreadStart(Print)); TInfo(th); th.Start(); Thread.Sleep(100); TInfo(th); th.Suspend(); Thread.Sleep(100); msg = "Thread ID: " + th.GetHashCode() + "\t 상태: " + th.ThreadState.ToString(); System.Windows.Forms.MessageBox.Show(msg); th.Resume(); Thread.Sleep(100); msg = "Thread ID: " + th.GetHashCode() + "\t 상태: " + th.ThreadState.ToString(); System.Windows.Forms.MessageBox.Show(msg); th.Abort(); th.Join(); TInfo(th); }
private void _ExcutePacket() { Logger.LogWarning($"开始协议记录线程:{m_packetThread.GetHashCode()}"); while (m_packetThread.IsAlive) { if (packets.Count > 0) { lock (packets) { var t = packets.Dequeue(); gameRecorder.Record(t.packet, t.frame); t.Free(); } } else if (m_pending) { if (!gameRecorder.reward) { Thread.Sleep(3000); } m_packetThread.Interrupt(); break; } else { Thread.Sleep(10); } } Logger.LogWarning($"结束协议记录线程:{m_packetThread.GetHashCode()}"); }
static void Main(string[] args) { Console.WriteLine(); Console.WriteLine("L01.p2"); Console.WriteLine(); Console.WriteLine("Start.. "); Thread secondThread = new Thread(Sound); // Так тоже можно secondThread.Start(); Thread currentThread = Thread.CurrentThread; currentThread.Name = "CurrentThread"; Console.WriteLine($"Thread: {currentThread.Name}, ID: {currentThread.GetHashCode()}"); for (int i = 0; i < 100; i++) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("- "); Thread.Sleep(5); } Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine($"\nThread: {currentThread.Name}, ID: {currentThread.GetHashCode()}, stopped"); Console.ReadKey(); }
private void _SaveToFile(object obj) { Logger.LogWarning($"开始文件保存线程:{m_saveThread.GetHashCode()}"); while (m_logThread != null && m_logThread.IsAlive) { Thread.Sleep(100); } while (m_packetThread != null && m_packetThread.IsAlive) { Thread.Sleep(100); } try { var fileName = (string)obj; if (string.IsNullOrWhiteSpace(fileName)) { fileName = FightRecordManager.NowTimeToFileName(); } try { if (m_packetThread != null) { gameRecorder._SaveToFile(fileName); SetSaveState(fileName + ".gr", SaveState.Complete); } } catch (Exception e) { Logger.LogError(e.ToString()); } try { if (m_logThread != null) { gameLogger.SaveToFile(fileName); SetSaveState(fileName + ".log", SaveState.Complete); } } catch (Exception e) { Logger.LogError(e.ToString()); } m_saveThread.Interrupt(); } catch (Exception e) { Logger.LogError(e.ToString()); } Logger.LogWarning($"结束文件保存线程:{m_saveThread.GetHashCode()}"); m_saveThread = null; }
private void Do(Runner runner) { Thread t = StartedThread(runner); Log("Thread #" + t.GetHashCode() + " started: interrupting it"); t.Interrupt(); Log("Thread #" + t.GetHashCode() + " interrupted"); runner.Interrupted(); Log("artificially signalled interruption"); Log("Joining thread #" + t.GetHashCode()); t.Join(); AssertIsPerformingStrategy(runner); }
static void Main(string[] args) { Console.WriteLine(); Console.WriteLine("L01.p4"); Console.WriteLine(); Thread currentThread = Thread.CurrentThread; currentThread.Name = "CurrentThread"; Console.WriteLine($"Thread: {currentThread.Name}, ID: {currentThread.GetHashCode()}"); #region Print Method var pth1 = new ParameterizedThreadStart(o => { Console.WriteLine($"Thread ID: {Thread.CurrentThread.ManagedThreadId} was started"); for (int i = 0; i < 10; i++) { Console.WriteLine(o); Thread.Sleep(100); } Console.WriteLine($"Thread ID: {Thread.CurrentThread.ManagedThreadId} was finished"); }); Thread thread1 = new Thread(pth1); thread1.Start("+ "); #endregion #region PrintBag Method ParameterizedThreadStart pth3 = new ParameterizedThreadStart(o => { p3.Bag bag = o as p3.Bag; Console.WriteLine($"Thread ID: {Thread.CurrentThread.ManagedThreadId} was started"); for (int i = 0; i < 10; i++) { Console.WriteLine($"BAG: {bag.Prop1} {bag.Prop2} {string.Format("{0:f}", bag.Prop3)}"); Thread.Sleep(100); } Console.WriteLine($"Thread ID: {Thread.CurrentThread.ManagedThreadId} was finished"); }); Thread thread3 = new Thread(pth3); thread3.Start(new p3.Bag(2, "second", 19.7)); #endregion Console.WriteLine($"\nThread: {currentThread.Name}, ID: {currentThread.GetHashCode()}, stopped"); Console.ReadKey(); }
public static int sum(int x, int y) { Thread thread = new Thread(new ThreadStart(HelloThread)); thread.Name = "MyThread"; int intThreadHashCode = thread.GetHashCode(); thread.Start(); //Console.WriteLine("Name & Hashcode of Thread : {0},{1}", thread.Name, intThreadHashCode); // Thread.Sleep(3000); Thread t2 = new Thread(new ThreadStart( delegate { add(x, y, true); } )); t2.Name = "Parameterized Thread"; int intT2HashCode = t2.GetHashCode(); t2.Start(); //Console.WriteLine("Name & Hashcode of Parameterized Thread : {0},{1}", t2.Name, intT2HashCode); return(add(x, y, false)); }
public static int Main(string[] args) { Console.Write("Do you want [1] or [2] threads? "); string threadCount = Console.ReadLine(); // Name the current thread. Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "Boss man"; Console.WriteLine("ID of {0} is: {1}", primaryThread.Name, primaryThread.GetHashCode()); // Make worker class. WorkerClass w = new WorkerClass(); if (threadCount == "2") { // Now make the thread. Thread backgroundThread = new Thread(new ThreadStart(w.DoSomeWork)); backgroundThread.Start(); } else { w.DoSomeWork(); } // Do some additional work. MessageBox.Show("I'm buzy"); return(0); }
public ServiceResult <int> WatermarkFile(byte[] msFile, string sUsername, string sCompany) { var result = new ServiceResult <int>() { Success = true }; try { DelWatermarkedFile delWatermarkedFile = new DelWatermarkedFile(delReturnFile); PrepareFileThread pft = new PrepareFileThread(new MemoryStream(msFile), delWatermarkedFile, sUsername, sCompany); Thread thread = new Thread(new ThreadStart(pft.Start)); thread.Start(); if (ThreadList == null) { ThreadList = new List <Thread>(); } result.Data = thread.GetHashCode(); ThreadList.Add(thread); } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.Message; } return(result); }
public bool InitializeSound(CameraListenerBase listener, FreeSL.FSL_SOUND_SYSTEM soundSystem) { lock (LockSync) { _listener = new FSLListener(listener); if (_initSound) { return(true); } if (!FreeSL.fslInit(soundSystem)) //Change if desire { return(false); } _initSound = true; /*FreeSL.ErrorCallbackDelegate ErrorDelegate = new FreeSL.ErrorCallbackDelegate(ErrorCallback); * GCHandle AllocatedDelegate = GCHandle.Alloc(ErrorDelegate); * FreeSL.fslSetErrorCallback(ErrorDelegate);*/ updaterThread = new Thread(new ThreadStart((UpdateSoundObjects))); updaterThread.Name = "Wof - sound updater thread " + updaterThread.GetHashCode(); updaterThread.Start(); return(true); } }
internal static void EndLoop(Thread thread) { #if DriverDebug Console.WriteLine("EndLoop({0:X}): Called", thread.GetHashCode()); #endif driver.EndLoop(thread); }
internal static object StartLoop(Thread thread) { #if DriverDebug Console.WriteLine("StartLoop({0:X}): Called", thread.GetHashCode()); #endif return(driver.StartLoop(thread)); }
//***************************************** /// <summary> IOCP Worker Function that calls the specified user function </summary> /// <exception cref = "Exception"> Unhandled Exception </exception> public void PostEvent() { // Only add work if we are not disposing if (IsDisposed) { return; } // Post an event into the IOCP Thread Pool PostQueuedCompletionStatus(GetHandle, 0, IntPtr.Zero, IntPtr.Zero); // Increment the number of item of work IncCurWorkInPool(); // Get a lock Monitor.Enter(GetCriticalSection); // If we have less than max threads currently in the pool if (GetCurThreadsInPool < GetMaxThreadsInPool) { // Should we add a new thread to the pool if (GetActThreadsInPool == GetCurThreadsInPool) { if (IsDisposed == false) { // Create a thread and start it var tsThread = new ThreadStart(IocpFunction); var thThread = new Thread(tsThread); thThread.Name = "IOCP " + thThread.GetHashCode(); thThread.Start(); // Increment the thread pool count IncCurThreadsInPool(); } } } // Release the lock Monitor.Exit(GetCriticalSection); }
public void Run() { try { listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port); listener.Start(); Console.WriteLine("Ожидание подключений..."); while (BC_is_Alive) { string ctID = $"{client_thread_ID}"; client_thread_ID++; TcpClient client = listener.AcceptTcpClient(); ClientObj CO = new ClientObj(client, ctID); Thread clientThread = new Thread(new ThreadStart(CO.ConnectionResolver)); clientThread.Start(); Console.WriteLine($"Клиент {clientThread.GetHashCode()} подключился"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (listener != null) { listener.Stop(); } } }
public override void OnTest(string[] args) { if (args.Length != 1) // 파라미터의 개수를 확인한다. { throw new ArgumentException("Parameter(s): <Port>"); } int echoServPort = Int32.Parse(args[0]); // 서버포트를 지정한다. // 클라이언트 연결 요청을 수락할 TcpListener 소켓 객체를 생성한다. TcpListener listener = new TcpListener(IPAddress.Any, echoServPort); ILogger logger = new ConsoleLogger(); // 콘솔창으로 메시지를 로깅한다. listener.Start(); // 무한히 실행하면서 연결 요청을 수락할 때마다 새로운 서비스 스레드를 생성한다. for (; ;) { try { Socket clntSock = listener.AcceptSocket(); // 연결 요청을 대기하면서 블록을 건다. EchoProtocol protocol = new EchoProtocol(clntSock, logger); Thread thread = new Thread(new ThreadStart(protocol.handleclient)); thread.Start(); logger.writeEntry("Created and started Thread = " + thread.GetHashCode()); } catch (System.IO.IOException e) { logger.writeEntry("Exception = " + e.Message); } } // 이곳으로는 도달하지 않는다. }
private static void Sound() { Thread soundThread = Thread.CurrentThread; soundThread.Name = "SoundThread"; Console.WriteLine($"Thread: {soundThread.Name}, ID: {soundThread.GetHashCode()}"); for (int i = 0; i < 100; i++) { Console.ForegroundColor = ConsoleColor.Green; Console.Write("+ "); Thread.Sleep(10); } Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine($"\nThread: {soundThread.Name}, ID: {soundThread.GetHashCode()}, stopped"); }
void threadPoolMaintanance() { // If we have less than max threads currently in the pool Should we add a new thread to the pool lock (padlock) { try { if (numberOfThreadsInPool < maxThreadsInPool) { if (numberOfActiveThreadsInPool == numberOfThreadsInPool) { if (isDisposed == false) { ThreadStart _threadStart = iocpFunction; Thread thThread = new Thread(_threadStart); thThread.Name = "IOCP " + thThread.GetHashCode(); thThread.Start(); IncrementNumberOfThreadsInPool(); } } } else { //TODO: Log: (CurThreadsInPool >= MaxThreadsInPool) } } catch { } } }
static void Main(string[] args) { Pub p = new Pub(); p.OnChange += (sender, e) => Console.WriteLine("Subscriber 1! Value:" + e.Value); p.OnChange += (sender, e) => Console.WriteLine("Subscriber 2! Value:" + e.Value); p.Raise(); int numarNaturalDat = 50000; PrimeNumbers primeNumbers = new PrimeNumbers(); Thread thread1 = new Thread(() => primeNumbers.getLesserPrimeNumber(numarNaturalDat, 0)); Thread thread2 = new Thread(() => primeNumbers.getLesserPrimeNumber(numarNaturalDat, 1)); try { thread1.Start(); Console.WriteLine("Startfir:" + thread1.GetHashCode() + " Time: " + DateTime.Now.ToString("HH:mm:ss:ffff") + " Numar natural dat = " + numarNaturalDat); thread2.Start(); Console.WriteLine("Startfir:" + thread2.GetHashCode() + " Time: " + DateTime.Now.ToString("HH:mm:ss:ffff") + " Numar natural dat = " + numarNaturalDat); } catch (Exception ex) when(ex is ThreadStateException || ex is OutOfMemoryException) { Console.WriteLine("Exception!"); } }
public void StartDispatching(TcpListener tcpListener, ILogger logger, IProtocolFactory protocolFactory, IAppDocument appDocument) { IServerProtocol serverProtocol; tcpListener.Start(); // Run forever, accepting and spawning threads to service each connection. for (; ;) { try { // Block waiting for a connection. Socket clientSocket = tcpListener.AcceptSocket(); serverProtocol = protocolFactory.CreateServerProtocol(clientSocket, logger); // A client has connected so create a thread to handle it. ParameterizedThreadStart clientThreadStart = new ParameterizedThreadStart(serverProtocol.HandleClientConnection); Thread clientThread = new Thread(clientThreadStart) { IsBackground = true }; clientThread.Start(); logger.WriteEntry("Created and started Thread = " + clientThread.GetHashCode()); } catch (System.IO.IOException ioException) { logger.WriteEntry("Exception = " + ioException.Message); } } // Unreachable. }
static void Main(string[] args) { // ссылка на экземпляр текущего потока Thread primary = Thread.CurrentThread; primary.Name = "Первичный"; // создаем вторичный поток Thread secondary = new Thread(WriteSecond); secondary.Start(); for (int i = 0; i < 10; i++) { Console.WriteLine("Имя Потока {0}, id {1} - {2} ", primary.Name, primary.GetHashCode(), i); Thread.Sleep(1500); } // создание нового потока занимает какое то время, в этот момент //выполнение основного потока программы не завершается secondary.IsBackground = true; // Console.ReadKey(); }
static void Main() { // Получаем ссылку на экземпляр текущего потока. Thread primaryThread = Thread.CurrentThread; // Присваиваем потоку имя. primaryThread.Name = "Primary"; // Выводим на экран информацию о текущем потоке. Console.WriteLine("ID потока {0}: {1}", primaryThread.Name, primaryThread.GetHashCode()); // Работа вторичного потока. Thread secondaryThread = new Thread(WriteSecond); secondaryThread.Start(); // Работа первичного потока. for (int counter = 0; counter < 10; counter++) { Console.WriteLine(primaryThread.Name + " " + counter); // Приостанавливаем выполнение текущего потока. Thread.Sleep(1500); } // Delay. Console.ReadKey(); }
/// <summary> /// Starts a given number of threads. Increases the number of threads in the threadpool. /// Note: shutdown of idle threads is handled by the threads themselves in ProcessQueue(). /// </summary> /// <param name="count">number of threads to start</param> private void StartThreads(int count) { // Don't start threads on shutdown if (!_run) { return; } lock (_syncObj) { for (int i = 0; i < count; i++) { // Make sure maximum thread count never exceeds if (_threads.Count >= _startInfo.MaximumThreads) { return; } Thread t = new Thread(ProcessQueue) { IsBackground = true }; t.Name = "Thread" + t.GetHashCode(); t.Priority = _startInfo.DefaultThreadPriority; t.Start(); ServiceRegistration.Get <ILogger>().Debug("ThreadPool.StartThreads(): Thread {0} started", t.Name); // Add thread as key to the Hashtable with creation time as value _threads[t] = DateTime.Now; } } }
/// <summary> /// 创建并开启work thread /// </summary> private void CreateAndStartWorkThread() { var thread = new Thread(WorkLoop); thread.Name = string.Format("IOCP Work Thread[{0}]", thread.GetHashCode()); thread.IsBackground = true; thread.Start(); }
/// <summary> /// 线程的使用 /// 线程函数通过委托传递,可以不带参数,也可以带参数(只能有一个参数),可以用一个类或结构体封装参数。 /// </summary> public static void OneThread() { Thread t = new Thread(new ThreadStart (() => { Console.WriteLine("thread operation"); })); Console.WriteLine(t.GetHashCode() + "thread start"); t.Start(); }
static void Main(string[] args) { int flag = 0; ParameterizedThreadStart p = new ParameterizedThreadStart(Print); Thread th1 = new Thread(p); Thread th2 = new Thread(p); Thread th3 = new Thread(p); Thread th4 = new Thread(p); Thread th5 = new Thread(p); th1.Priority = ThreadPriority.Lowest; th2.Priority = ThreadPriority.Lowest; th3.Priority = ThreadPriority.Lowest; th4.Priority = ThreadPriority.Highest; th5.Priority = ThreadPriority.Lowest; th1.Start(1); th2.Start(2); th3.Start(3); th4.Start(4); th5.Start(5); do { //Thread.Sleep(0); //Thread.Sleep(10); //Thread.Sleep(1); Console.WriteLine("----" + flag + "----"); if (Thread.CurrentThread.IsAlive) { Console.WriteLine("Main thread " + Thread.CurrentThread.GetHashCode()); } if (th1.IsAlive) { Console.WriteLine("Thread 1 " + th1.GetHashCode()); } if (th2.IsAlive) { Console.WriteLine("Thread 2 " + th2.GetHashCode()); } if (th3.IsAlive) { Console.WriteLine("Thread 3 " + th3.GetHashCode()); } if (th4.IsAlive) { Console.WriteLine("Thread 4 " + th4.GetHashCode()); } if (th5.IsAlive) { Console.WriteLine("Thread 5 " + th5.GetHashCode()); } flag++; } while (flag < 5000); Console.WriteLine("The End"); Console.ReadKey(); }
static void Main(string[] args) { Thread thread = Thread.CurrentThread; Console.WriteLine(thread.IsAlive); Console.WriteLine(thread.Name); Console.WriteLine(thread.GetHashCode()); Process.Start("https://www.facebook.com/"); }
public void startDispatching(TcpListener listener, ILogger logger, IProtocolFactory protoFactory) { // Create N threads, each running an iterative server for (int i = 0; i < numThreads; i++) { DispatchLoop dl = new DispatchLoop(listener, logger, protoFactory); Thread thread = new Thread(new ThreadStart(dl.rundispatcher)); thread.Start(); logger.writeEntry("Created and started Thread = " + thread.GetHashCode()); } }
public void startDispatching(TcpListener listener, ILogger logger, IProtocolFactory protoFactory) { // Run forever, accepting and spawning threads to service each connection for (;;) { try { listener.Start(); Socket clntSock = listener.AcceptSocket(); // Block waiting for connection IProtocol protocol = protoFactory.createProtocol(clntSock, logger); Thread thread = new Thread(new ThreadStart(protocol.handleclient)); thread.Start(); logger.writeEntry("Created and started Thread = " + thread.GetHashCode()); } catch (System.IO.IOException e) { logger.writeEntry("Exception = " + e.Message); } } /* NOT REACHED */ }