// Initialize Parallel class's instance creating required number of threads // and synchronization objects private void Initialize( ) { threadsCount = System.Environment.ProcessorCount; //No point starting new threads for a single core computer if (threadsCount <= 1) { return; } // array of events, which signal about available job jobAvailable = new AutoResetEvent[threadsCount]; // array of events, which signal about available thread threadIdle = new ManualResetEvent[threadsCount]; // array of threads threads = new Thread[threadsCount]; for ( int i = 0; i < threadsCount; i++ ) { jobAvailable[i] = new AutoResetEvent( false ); threadIdle[i] = new ManualResetEvent( true ); threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) ); threads[i].IsBackground = false; threads[i].Start( i ); } }
[System.Security.SecurityCritical] // auto-generated private int RunInNewThread () { Thread th = new Thread(new ThreadStart(NewThreadRunner)); th.SetApartmentState(m_apt); th.Start(); th.Join(); return m_runResult; }
public void Instance_is_reused_on_same_thread_when_controlled_by_threadsingleton_lifecycle() { var builder = new ContainerBuilder(); builder.DefaultControlledBy<ThreadSingletonLifecycle>(); builder.Register<IFoo, Foo>(); builder.Register<IBar, Bar>(); var container = builder.Build(); var threadData = new ThreadData(container); var thread = new Thread(threadData.ResolveFoosWithContainer); var threadDataTwo = new ThreadData(container); var threadTwo = new Thread(threadDataTwo.ResolveFoosWithContainer); thread.Start(); threadTwo.Start(); thread.Join(); threadTwo.Join(); Assert.IsTrue(ReferenceEquals(threadData.FooOne, threadData.FooTwo)); Assert.IsFalse(ReferenceEquals(threadData.FooOne, threadDataTwo.FooOne)); }
public static void SetClipboard(string result) { var thread = new Thread(() => Clipboard.SetText(result)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); }
public RelayPort(Cpu.Pin pin, bool initialState, int timeout) : base(pin, initialState) { currentstate = initialState; relayThread = new Thread(new ThreadStart(RelayLoop)); relayThread.Start(); }
public void SetUp() { runner = new TestRunner(x => x.AddFixture<SlowFixture>()); test = new Test("slow test").With(Section.For<SlowFixture>().WithStep("GoSlow")); var reset = new ManualResetEvent(false); var running = new ManualResetEvent(false); var thread = new Thread(() => { running.Set(); Debug.WriteLine("Starting to run"); test.LastResult = runner.RunTest(new TestExecutionRequest() { Test = test, TimeoutInSeconds = 60 }); test.LastResult.ShouldNotBeNull(); Debug.WriteLine("finished running"); reset.Set(); }); thread.Start(); running.WaitOne(); Thread.Sleep(1000); Debug.WriteLine("Aborting now!"); runner.Abort(); Debug.WriteLine("Done aborting"); reset.WaitOne(5000); test.LastResult.ShouldNotBeNull(); Debug.WriteLine("completely done"); }
private void setupRequestResponseBackgroundThead() { requestResponseThread = new Thread(new ThreadStart(RequestResponseBackground_Thread)); requestResponseThread.IsBackground = true; multicastRequestThread = new Thread(new ThreadStart(MulticastRequestBackgroud_Thread)); multicastRequestThread.IsBackground = true; }
public static void Start(string logFolder) { _logFolder = logFolder; LogEntryFileWriter.LogFolder = _logFolder; Thread monitorThread = new Thread(new ThreadStart(Monitor)); monitorThread.Start(); }
public Service() { var filePath = ConfigurationManager.AppSettings["FolderPath"]; var fileExtension = ConfigurationManager.AppSettings["FileExtension"]; var dataManager = new DataManager(new Watcher(filePath, fileExtension)); _workerThread = new Thread(dataManager.OnStart); }
/// <summary> /// Starts listening incoming connections. /// /// </summary> public override void Start() { this.StartSocket(); this._running = true; this._thread = new Thread(new ThreadStart(this.DoListenAsThread)); this._thread.Start(); }
// GET api/values?q=Microsoft.ApplicationInsights public string Get([FromUri]string q) { Thread t = new Thread(new ThreadStart( () => { IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2"); List<IPackage> packages = repo.Search(q, true).ToList(); foreach (var p in packages) { lock (packagesListLock) { if (!this.packagesList.Contains(p.Id)) { this.packagesList.Add("Search '" + q + "'", p); } } Thread.Sleep(10); } })); t.Start(); return Process.GetCurrentProcess().Id.ToString(); }
private static void CheckForLoops(IEnumerable<Activity> activities) { var isCaughtProperly = false; var thread = new System.Threading.Thread( () => { try { activities.CriticalPath(p => p.Predecessors, l => (long)l.Duration); } catch (System.InvalidOperationException ex) { System.Console.WriteLine("Found problem: " + ex.Message); isCaughtProperly = true; } } ); thread.Start(); for (var i = 0; i < 100; i++) { Thread.Sleep(100); // Wait for 10 seconds - our thread should finish by then if (thread.ThreadState != ThreadState.Running) break; } if(thread.ThreadState ==ThreadState.Running) thread.Abort(); System.Console.WriteLine(isCaughtProperly ? "Critical path caught the loop" : "Critical path did not find the loop properly"); }
private ThreadPool(int queueSize, int threadNum) { #if UNITY_WEBPLAYER threadNum = 1; #else if (threadNum == 0) { threadNum = SystemInfo.processorCount; } #endif m_threadPool = new Thread[threadNum]; m_taskQueue = new TaskInfo[queueSize]; m_nPutPointer = 0; m_nGetPointer = 0; m_numTasks = 0; m_putNotification = new AutoResetEvent(false); m_getNotification = new AutoResetEvent(false); #if !UNITY_WEBPLAYER if (1 < threadNum) { m_semaphore = new Semaphore(0, queueSize); for (int i = 0; i < threadNum; ++i) { m_threadPool[i] = new Thread(ThreadFunc); m_threadPool[i].Start(); } } else #endif { m_threadPool[0] = new Thread(SingleThreadFunc); m_threadPool[0].Start(); } }
public void TestHelloWorld() { var webMethod = new model.WebSvcMethod("HelloWorld", TestDataReader.Instance.ServiceUri); webMethod.Request = new model.WebSvcMessageRequest(); webMethod.Request.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_TYPE] = "text/xml; charset=utf-8"; webMethod.Request.Headers[model.WebSvcMessageRequest.HEADER_NAME_SOAP_ACTION] = "http://tempuri.org/ICallSyncOpService/HelloWorld"; webMethod.Request.Body = TestDataReader.Instance.RequestResponseMessages["HelloWorldRequest"]; var call = new process.WebSvcAsync.Operations.CallAsyncOp(webMethod); call.OnComplete += call_OnComplete; var thread = new Thread(() => { call.Start(); }); thread.Name = "TestHelloWorld Thread"; thread.Start(); thread.Join(); var contentLengthResult = _testHelloWorldResult.Response.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_LENGTH]; var contentTypeResult = _testHelloWorldResult.Response.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_TYPE]; Assert.AreEqual("211", contentLengthResult); Assert.AreEqual("text/xml; charset=utf-8", contentTypeResult); Assert.AreEqual(_testHelloWorldResult.Response.BodyUnformatted, TestDataReader.Instance.RequestResponseMessages["HelloWorldResponse"]); Assert.AreEqual(_testHelloWorldResult.Response.Status, "200 OK"); }
public void MultiThread() { int threadCount = 5; _threadedMessageCount = 100; int totalMessageCount = threadCount * _threadedMessageCount; List<Thread> threads = new List<Thread>(); for (int thread = 0; thread < threadCount; thread++) { Thread t = new Thread(new ThreadStart(SendMessageThread)); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } POP3ClientSimulator.AssertMessageCount(_account.Address, "test", totalMessageCount); for (int i = 0; i < totalMessageCount; i++) { string content = POP3ClientSimulator.AssertGetFirstMessageText(_account.Address, "test"); Assert.IsTrue(content.Contains("X-Spam-Status"), content); } }
public MessageQueue() { _running = true; _processMessageHandlers = new List<ProcessMessageHandler>(); _messageQueueThread = new Thread(new ThreadStart(processQueue)); _messageQueueThread.Start(); }
protected override void ProcessRecord() { base.ProcessRecord(); ExecutionResult result; if (Thread.CurrentThread.GetApartmentState() == this.Apartment) { result = ExecuteExpression(this.Expression); } else { var ApartmentThread = new System.Threading.Thread(StartExecuteExpression); ApartmentThread.SetApartmentState(this.Apartment); var Parameters = new ExecutionParameters { Expression = this.Expression }; ApartmentThread.Start(Parameters); ApartmentThread.Join(); result = Parameters.Result; } if (result == null) throw new InvalidOperationException("No result returned."); if (result.Error != null) throw result.Error; if (result.Output != null) WriteObject(result.Output); }
public Service() { InitializeComponent(); _server = new ConnectsterServer(); var job = new ThreadStart(_server.Start); _thread = new Thread(job); }
public TcpServer(int port, Encoding enc) { listener = new TcpListener(port); listenThread = new Thread(ListenThreadFun); listenThread.Start(); encoder = enc; }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // set the seed manually. OsmSharp.Math.Random.StaticRandomGenerator.Set(116542346); // add the to-ignore list. OsmSharp.Logging.Log.Ignore("OsmSharp.Osm.Interpreter.SimpleGeometryInterpreter"); OsmSharp.Logging.Log.Ignore("CHPreProcessor"); OsmSharp.Logging.Log.Ignore("RTreeStreamIndex"); OsmSharp.Logging.Log.Ignore("Scene2DLayeredSource"); // register the textview listener OsmSharp.Logging.Log.Enable(); OsmSharp.Logging.Log.RegisterListener( new TextViewTraceListener(this, FindViewById<TextView>(Resource.Id.textView1))); // do some testing here. Thread thread = new Thread( new ThreadStart(Test)); thread.Start(); }
//UI Init and Main Thread Creation public mainForm() { InitializeComponent(); AcceptButton = buttonSend; tmain = new System.Threading.Thread(main); tmain.Start(); }
/// <summary> /// Setups the primary display form. /// </summary> public static void SetupPrimaryDisplayForm() { PrimaryDisplayForm = new DisplayForm(800, 600); Thread thread = new Thread(new ThreadStart(CreatePrimaryDisplayForm)); thread.Start(); }
public void Start_WhenExecutedInMultipleThreads_ShouldBeThreadSafeAndNotExecuteSameTaskTwice() { const string resultId = "result/1"; Enumerable.Range(1, 100) .ToList() .ForEach(i => { CreateRaceConditionTask(resultId); var thread1 = new Thread(() => { var taskExecutor = MasterResolve<ITaskExecutor>(); taskExecutor.Start(); }); var thread2 = new Thread(() => { var taskExecutor = MasterResolve<ITaskExecutor>(); taskExecutor.Start(); }); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); }); var result = Store.Load<ComputationResult<int>>(resultId); result.Result.Should().Be(100); }
public void Start() { Stop(); m_bThreadStop = false; m_thread = new System.Threading.Thread(Main); m_thread.Start(); }
private static void Main(string[] args) { var n = 10; var chickenFarm = new ChickenFarm(); var token = chickenFarm.GetToken(); var chickenFarmer = new Thread(chickenFarm.FarmSomeChickens) {Name = "TheChickenFarmer"}; var chickenStore = new Retailer(token); chickenFarm.PriceCut += chickenStore.OnPriceCut; var retailerThreads = new Thread[n]; for (var index = 0; index < retailerThreads.Length; index++) { retailerThreads[index] = new Thread(chickenStore.RunStore) {Name = "Retailer" + (index + 1)}; retailerThreads[index].Start(); while (!retailerThreads[index].IsAlive) { ; } } chickenFarmer.Start(); chickenFarmer.Join(); foreach (var retailerThread in retailerThreads) { retailerThread.Join(); } }
static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage:"); Console.WriteLine("'extractor.exe output_folder input.xef' to extract a .xef file."); return; } string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); string subFolderPath = System.IO.Path.Combine(myPhotos, args[0]); Directory.CreateDirectory(subFolderPath); using (Extractor extractor = new Extractor(subFolderPath)) { extractor.ListenForFrames(); string xefFileName = args[1]; Console.WriteLine("Extracting frames from .xef file: {0}", xefFileName); Player player = new Player(xefFileName); Thread playerThread; playerThread = new System.Threading.Thread(new ThreadStart(player.PlayXef)); playerThread.Start(); playerThread.Join(); extractor.Stop(); } }
public void ClassReRegisteredFromClassToObjectFactory_Success() { var c = new Container(); c.RegisterType<EmptyClass>().AsPerThread(); EmptyClass emptyClass1 = null; EmptyClass emptyClass2 = null; EmptyClass emptyClass3 = null; EmptyClass emptyClass4 = null; var thread = new Thread(() => { emptyClass1 = c.Resolve<EmptyClass>(ResolveKind.PartialEmitFunction); emptyClass2 = c.Resolve<EmptyClass>(ResolveKind.PartialEmitFunction); c.RegisterType<EmptyClass>(() => new EmptyClass()).AsPerThread(); emptyClass3 = c.Resolve<EmptyClass>(ResolveKind.PartialEmitFunction); emptyClass4 = c.Resolve<EmptyClass>(ResolveKind.PartialEmitFunction); }); thread.Start(); thread.Join(); Assert.AreEqual(emptyClass1, emptyClass2); Assert.AreEqual(emptyClass3, emptyClass4); Assert.AreNotEqual(emptyClass1, emptyClass3); }
public static void StartService() { Thread thread = new Thread(OrderProcessingService.Run); thread.Name = "Order Processing Thread"; thread.IsBackground = true; thread.Start(); }
public RelayPort(Cpu.Pin pin, bool initialState, bool glitchFilter, Port.ResistorMode resistor, int timeout) : base(pin, initialState, glitchFilter, resistor) { currentstate = initialState; relayThread = new Thread(new ThreadStart(RelayLoop)); relayThread.Start(); }
public ItemManageForm() { this.InitializeComponent(); DB = new StoreDBEntities(); Control.CheckForIllegalCrossThreadCalls = false; this.T = new System.Threading.Thread(new System.Threading.ThreadStart(this.FixCounts)); }
public RaceTest(bool autoReset) { timer = new Timer(); timer.AutoReset = autoReset; timer.Interval = 100; timer.Elapsed += new ElapsedEventHandler(Tick); timer.Start(); ST.Thread[] tl = new ST.Thread [Threads]; for (int i = 0; i < Threads; i++) { tl [i] = new ST.Thread(new ST.ThreadStart(Run)); tl [i].Start(); } for (int i = 0; i < Threads; i++) { tl [i].Join(); } ST.Thread.Sleep(1000); }
private void button2_Click(object sender, EventArgs e) { load = new System.Threading.Thread(loadingWindow); load.Start(); try { listBox1.Items.Clear(); goog.loadSentMessages(); foreach (KeyValuePair <string, userMessages> mess in goog.allMessages) { if (mess.Value.FOLDER == "SENT") { listBox1.Items.Add(mess.Value); } } listBox1.DisplayMember = "TITLE"; } catch (Exception Exc) { Debug.WriteLine("1" + Exc); } load.Abort(); }
/// <summary> /// Select output folder by FolderBrowserDialog /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SaveToToolStripMenuItem_Click(object sender, EventArgs e) { if (null != _htmlFiles && _htmlFiles.Count > 0) { FolderBrowserDialog folderBrowerDialog = new FolderBrowserDialog(); if (DialogResult.OK == folderBrowerDialog.ShowDialog()) { _outputFolder = folderBrowerDialog.SelectedPath; if (!Directory.Exists(_inputFolder)) { Directory.CreateDirectory(_inputFolder); } SetLabelValue(toolStripStatusLabelStatusValue, Status.Processing.ToString()); _processThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.WordToFile)); timer.Start(); _processThread.Start(); } } else { MessageBox.Show("Please Open input folder containing HTML files."); } }
/// <summary> /// Tick loop on worker thread /// </summary> private void TickAsyncMain() { try { while (true) { if (bCancelTicker != 0) { return; } ThreadHelper.Generic.BeginInvoke(Tick); if (bCancelTicker != 0) { return; } Thread.Sleep(TickPeriod); } } catch (ThreadAbortException) { } }
/// <summary> /// Constructor for a ClientMarketData when used as a component. /// </summary> public ClientMarketData() : base() { #if DEBUG // This will insure that the background thread to access the server isn't spawned when in the design mode. if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { #endif if (ClientMarketData.InstanceCount == 1) { // This thread is used to access the database for the objects that this user has access to. The end product of this // thread is a tree structure that contains the hierarchy of objects (accounts, users, trading desks, securities, etc.) // that the user can navigate. The results are passed back to this thread through the delegate procedure 'objectNode' // after the control window is created. threadBackground = new Thread(new ThreadStart(ReconcilliationThread)); threadBackground.Name = "ClientMarketData Background"; threadBackground.Start(); } #if DEBUG } #endif }
public BackgroundScanner( IVsOutputWindowPane outputPane, BuildStatusContainer buildStatusContainer ) { if (outputPane is null) { throw new ArgumentNullException(nameof(outputPane)); } if (buildStatusContainer is null) { throw new ArgumentNullException(nameof(buildStatusContainer)); } _outputPane = outputPane; _buildStatusContainer = buildStatusContainer; _cancellationTokenSource = new CancellationTokenSource(); _scanTask = new Thread( () => PerformScanBackground() ); }
static void Main(string[] args) { //1)send Immediate //var req = new SimpleRequestImmediate(); //var req = new RequestImmediateAndEvent(); //2)send NoImmediate() //var req = new SimpleRequestNOImmediate(); var req = new RequestNOImmediateAndEvent(); var rep = new Rep(); var requestThread = new System.Threading.Thread(req.Init); //var responseThread = new System.Threading.Thread(rep.Init); //responseThread.Start(); //Thread.Sleep(10000); requestThread.Start(); Console.ReadLine(); }
private void startup() { dolog(); if (DSplugin) { timer1 = new Thread(timer); timer1.IsBackground = true; timer1.Start(); return; } try { th.Abort(); } catch { } th = new System.Threading.Thread(delegate() { StartCapture(); }); th.Name = "Video Thread"; th.Start(); }
/// <summary> /// 启动线程 /// </summary> public void Start() { if (!_isRun) { _isRun = true; PointSsz = new List <string>(); _rwLocker = new ReaderWriterLock(); //读取所有设备、数据状态枚举类型 var response = graphicsbaseinfService.GetAllDeviceEnumcode(); dtStateVal = response.Data; DevInfos = devService.GetAllDeviceDefineCache().Data; m_PointSszThread = new Thread(setAllPointSszThread); //object o = mx; m_PointSszThread.Start(); //注册关闭事件 RequestUtil.OnMainFormCloseEvent += new RequestUtil.OnMainFormClose(MainFormCloseEvent); } }
/// <summary> /// https://stackoverflow.com/questions/518701/clipboard-gettext-returns-null-empty-string /// </summary> /// <remarks>Only works when apartmentState is STA</remarks> /// <returns></returns> public string GetClipboardText() { IDataObject idat = null; // ReSharper disable once NotAccessedVariable Exception threadEx = null; object text = ""; System.Threading.Thread staThread = new System.Threading.Thread( delegate() { try { idat = Clipboard.GetDataObject(); text = idat?.GetData(DataFormats.Text); } catch (Exception ex) { threadEx = ex; } }); staThread.SetApartmentState(ApartmentState.STA); staThread.Start(); staThread.Join(); return(text as string); }
private void modoMoverToolStripMenuItem_Click(object sender, EventArgs e) { if (modoMoverToolStripMenuItem.Checked == true) { if (ThreadSkype != null) { ThreadSkype.Abort(); } ModoMover = true; Sizer.Visible = true; FormHandler_FrmPrincipalShow(); } else { if (ThreadSkype != null) { ThreadSkype = new System.Threading.Thread(SkypeRunning); ThreadSkype.Start(); } ModoMover = false; Sizer.Visible = false; } }
private static byte[] GetAudio(string response) { byte[] buffer = new byte[0]; if (!string.IsNullOrWhiteSpace(response)) { var t = new System.Threading.Thread(() => { using (MemoryStream memoryStream = new MemoryStream()) { SpeechSynthesizer synth = new SpeechSynthesizer(); synth.SetOutputToWaveStream(memoryStream); synth.Speak(response); buffer = memoryStream.ToArray(); } }); t.Start(); t.Join(); } return(buffer); }
private static void LoadServerBackground(Object param) { Forms.LoadingUI loading = param as Forms.LoadingUI; System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(LoadDatasBackground)); t.Name = "Data Load Thread"; t.Start(loading); resetEvent.WaitOne(); Globals.MainUI = new Forms.MainUI(); loading.UpdateStatus("Initializing TCP..."); NetworkManager.Initialize(); NetworkManager.TcpListener.Listen(System.Net.IPAddress.Any, Settings.GamePort); loading.Close(true); if (LoadComplete != null) { LoadComplete(null, EventArgs.Empty); } }
//---------------------------------------------------------------------- // Internal Methods //---------------------------------------------------------------------- /// <summary> /// Used for trace events that the test system does not want published. /// /// Example debug only statements. /// </summary> /// <param name="format">A format string used to build the message. /// </param> /// <param name="args">A list of arguments for the format string. /// </param> internal static void InternalTrace(string format, params object[] args) { // If there are no args, the given string should be treated as literal. // Otherwise, if it happens to be a GUID like {001B...}, we'd get an exception from string.Format() // because it sees a format specifier in the string. string message = args.Length == 0 ? format : string.Format(CultureInfo.CurrentCulture, format, args); System.Threading.Thread current = System.Threading.Thread.CurrentThread; message = string.Format( CultureInfo.CurrentCulture, "[D:{0}][T:{1}]{2}", AppDomain.CurrentDomain.IsDefaultAppDomain() ? "Default" : AppDomain.CurrentDomain.FriendlyName, current.IsThreadPoolThread ? current.ManagedThreadId.ToString() : current.Name, message); Current.RaiseMessageSent( MessageEventArgs.MessageCategory.Internal, message); }
public static void SendUserLogByUDP(string userID, string loginName, string userFullName, string pMyIP, string programTitle, string logContent, string programID, LogDatabaseDll.LogDatabaseWS.E_Operation oper, LogDatabaseDll.LogDatabaseWS.E_System sys) { string message = "Xstudio;" + userFullName + ";" + myIP + ";" + (int)oper + ";" + programTitle; try { userID1 = userID; loginName1 = loginName; userFullName1 = userFullName; programTitle1 = programTitle; logContent1 = logContent; programID1 = programID.Trim().Length == 0 ? Guid.Empty.ToString() : programID.Trim(); myIP = pMyIP; oper1 = oper; sys1 = sys; System.Threading.Thread th = new System.Threading.Thread(new ThreadStart(writeLog)); th.Start(); } catch { } }
public bool ConnectRelease() { // Releases a current connected PCAN-Basic channel // TPCANStatus _status = PCANBasic.Uninitialize(m_PcanHandle); if (_status == TPCANStatus.PCAN_ERROR_OK) { //tmrRead.Enabled = false; if (m_ReadThread != null) { m_ReadThread.Abort(); m_ReadThread.Join(); m_ReadThread = null; } return(true); } return(false); // Sets the connection status of the main-form // //SetConnectionStatus(false); }
/// <summary> /// Dispatch all queued items /// </summary> public static void DispatchAll() { Dispatcher callbacks; System.Action action; while (actionQueue.TryDequeue(out callbacks)) { callbacks.Dispatch(); } while (mainActionQueue.TryDequeue(out action)) { action(); } if (thread == null && !itemizedWork.IsEmpty) { thread = new Thread(ExecuteThread); thread.Start(); } }
/// <summary> /// Creates the application and starts it, returning the an instance (child of <see cref="Form"/>). /// </summary> public static ApplicationSimulator Create() { ApplicationSimulator instace_holder = null; var holder = new ManualResetEvent(false); var t = new Thread(() => Application.Run( instace_holder = new ApplicationSimulator(inst => { instace_holder = (ApplicationSimulator)inst; holder.Set(); } ))); t.SetApartmentState(ApartmentState.STA); t.IsBackground = true; t.Start(); _rewait: try { holder.WaitOne(); //wait for init. } catch { Thread.Sleep(5); goto _rewait; } return(instace_holder); }
/*private void OnTestGetFrame(object sender, EventArgs e) * { * //m_bCancelOperation = false; * // m_lblMessage.Text = "Put finger to the scanner"; * * * GetFrame(); * //MessageDlg.HideMessageDlg(); * if (m_Frame != null && m_Frame.Length != 0) * { * Size size = m_hDevice.ImageSize; * Graphics gr = m_picture.CreateGraphics(); * Bitmap hBitmap = CreateBitmap(gr.GetHdc(), size, m_Frame); * hBitmap.RotateFlip(RotateFlipType.Rotate180FlipX); * m_picture.Image = hBitmap; * } * * * * }*/ private void OnTestGetFrame(object sender, EventArgs e) { //m_bCancelOperation = false; // m_lblMessage.Text = "Put finger to the scanner"; SaveFrame.Enabled = true; fingerprint = true; m_btnGetFrame.Enabled = false; m_btnCancel.Enabled = true; System.Threading.Thread thread = new System.Threading.Thread(GetFrame); thread.Start(); System.Threading.Thread.Sleep(5); //GetFrame(); //MessageDlg.HideMessageDlg(); /*if (m_Frame != null && m_Frame.Length != 0) * { * Size size = m_hDevice.ImageSize; * Graphics gr = m_picture.CreateGraphics(); * Bitmap hBitmap = CreateBitmap(gr.GetHdc(), size, m_Frame); * hBitmap.RotateFlip(RotateFlipType.Rotate180FlipX); * m_picture.Image = hBitmap; * }*/ }
/// ***************************************************************************** /// <summary> /// Translation of kernel32:SetThreadUILanguage semantics into managed code. /// Used for overridding console CurrentUICulture when console code page /// doesn't match the current ANSI or OEM code page. /// </summary> /// ***************************************************************************** public static void SetConsoleUICulture() { int iConsoleCodePage = System.Console.Out.Encoding.CodePage; System.Threading.Thread currentThread = Thread.CurrentThread; // // if no code page set, we're not in a console // if (0 != iConsoleCodePage) { if (!((iConsoleCodePage == currentThread.CurrentCulture.TextInfo.ANSICodePage || iConsoleCodePage == currentThread.CurrentCulture.TextInfo.OEMCodePage) && (iConsoleCodePage == currentThread.CurrentUICulture.TextInfo.ANSICodePage || iConsoleCodePage == currentThread.CurrentUICulture.TextInfo.OEMCodePage))) { // // override with en-US culture // currentThread.CurrentUICulture = new CultureInfo("en-US"); } } }
void loopWithWaiting() { /*while (true) { * myTick(true); * Thread.Sleep(1); * } * closingStuff();*/ Thread extraWindowThread; extraWindowThread = new System.Threading.Thread(delegate() { while (myTick(true)) { //int myData = 0; //myTick(true); //tick(0, 0, ref myData, 0, 0); Thread.Sleep(50); } closingStuff(); CloseGame(); }); extraWindowThread.Start(); }
private void BUT_DLall_Click(object sender, EventArgs e) { if (status == SerialStatus.Done) { if (CHK_logs.Items.Count == 0) { // try again... LoadLogList(); return; } BUT_DLall.Enabled = false; BUT_DLthese.Enabled = false; int[] toDownload = GetAllLogIndices().ToArray(); try { Directory.CreateDirectory(Settings.Instance.LogDir); } catch (Exception ex) { AppendSerialLog(string.Format(LogStrings.LogDirectoryError, Settings.Instance.LogDir) + "\r\n" + ex.Message); return; } AppendSerialLog(string.Format(LogStrings.DownloadStarting, Settings.Instance.LogDir)); System.Threading.Thread t11 = new System.Threading.Thread( delegate() { DownloadThread(toDownload); }) { Name = "Log Download All thread" }; t11.Start(); } }
/// <summary>Initialize the thread pool.</summary> static ManagedThreadPool() { int configMaxWorkerThreads = 0; try { configMaxWorkerThreads = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings ["QueuedThreads"]); if (configMaxWorkerThreads > 0) { _maxWorkerThreads = configMaxWorkerThreads; } } catch {} // Create our thread stores; we handle synchronization ourself // as we may run into situtations where multiple operations need to be atomic. // We keep track of the threads we've created just for good measure; not actually // needed for any core functionality. _waitingCallbacks = new Queue(); _workerThreads = new ArrayList(); _inUseThreads = 0; // Create our "thread needed" event _workerThreadNeeded = new Semaphore(0); // Create all of the worker threads for (int i = 0; i < _maxWorkerThreads; i++) { // Create a new thread and add it to the list of threads. System.Threading.Thread newThread = new System.Threading.Thread(new ThreadStart(ProcessQueuedItems)); _workerThreads.Add(newThread); // Configure the new thread and start it newThread.Name = "ManagedPoolThread #" + i.ToString(); newThread.IsBackground = true; newThread.Start(); } }
void Accept(object ias) { while (true) { Socket handler = listener.Accept(); //if (listener == null) // return; //Socket handler = listener.EndAccept(ar); // Create the state object. NETcollection netc = new NETcollection(); netc.Soc = handler; listconn.Add(netc); System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(UpdataConnSoc)); t.Start(handler); System.Threading.Thread.Sleep(50); // handler.BeginReceive(netc.Buffer, 0, netc.BufferSize, 0, new AsyncCallback(ReadCallback2), netc); //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(UpdataConnSoc), handler); // Set the event to nonsignaled state. //allDone.Reset(); ////开启异步监听socket //// Console.WriteLine("Waiting for a connection"); //try //{ // listener.BeginAccept( // new AsyncCallback(AcceptCallback), // listener); System.Threading.Thread.Sleep(1); //} //catch { } //// 让程序等待,直到连接任务完成。在AcceptCallback里的适当位置放置allDone.Set()语句. //allDone.WaitOne(); } }
public void WebProjectInstallOnNew() { using (var app = new PythonVisualStudioApp()) { Pip.Uninstall(app.ServiceProvider, app.OptionsService.DefaultInterpreter, "bottle", false) .WaitAndUnwrapExceptions(); var t = Task.Run(() => app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.BottleWebProjectTemplate, TestData.GetTempPath(), "WebProjectInstallOnNew", suppressUI: false )); using (var dlg = new AutomationDialog(app, AutomationElement.FromHandle(app.WaitForDialog(t)))) { // Install to active environment dlg.ClickButtonAndClose("CommandLink_1001", nameIsAutomationId: true); } var project = t.WaitAndUnwrapExceptions(); Assert.AreSame(app.OptionsService.DefaultInterpreter, project.GetPythonProject().ActiveInterpreter); for (int retries = 60; retries > 0; --retries) { if (project.GetPythonProject().ActiveInterpreter.FindModules("bottle").Any()) { break; } Thread.Sleep(1000); } AssertUtil.ContainsExactly(project.GetPythonProject().ActiveInterpreter.FindModules("bottle"), "bottle"); Pip.Uninstall(app.ServiceProvider, app.OptionsService.DefaultInterpreter, "bottle", false) .WaitAndUnwrapExceptions(); } }
public void TestCancel() { PythonPaths.Python27_x64.AssertInstalled(); PythonPaths.Python33_x64.AssertInstalled(); var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = TestInfo.TestAdapterATests.Union(TestInfo.TestAdapterBTests).ToArray(); var testCases = expectedTests.Select(tr => tr.TestCase); var thread = new System.Threading.Thread(o => { executor.RunTests(testCases, runContext, recorder); }); thread.Start(); // One of the tests being run is hard coded to take 10 secs Assert.IsTrue(thread.IsAlive); System.Threading.Thread.Sleep(100); executor.Cancel(); System.Threading.Thread.Sleep(100); // It should take less than 10 secs to cancel // Depending on which assemblies are loaded, it may take some time // to obtain the interpreters service. Assert.IsTrue(thread.Join(10000)); System.Threading.Thread.Sleep(100); Assert.IsFalse(thread.IsAlive); // Canceled test cases do not get recorded Assert.IsTrue(recorder.Results.Count < expectedTests.Length); }
//启动以太网客户端与服务器进行通讯 /// <summary> /// 启动以太网客户端与服务器进行通讯 /// </summary> public void Start() { if (PasswordIsCorrect == false) { MessageBox.Show("Right Prohibited.\r\n You don't have the given right to use this DLL library, please contact with ThomasPeng.\r\n你未得到授权的密码,无法使用此DLL进行软件开发!请与作者彭东南联系:[email protected]\r\n 版权所有: 彭东南", "非法操作", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } try { if (SuccessBuiltNew == true) { if (ClientConnectToServerThread == null) { ClientConnectToServerThread = new System.Threading.Thread(ClientReadMessageFromServer); ClientConnectToServerThread.IsBackground = true; ClientConnectToServerThread.Start(); ErrorMessage = "启动以太网客户端..."; } else { ErrorMessage = "已经启动了以太网客户端,不需要重复开启..."; } } else { ErrorMessage = "未成功创建以太网客户端类的实例!"; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void DoJoin(string id, string pw, string mail, string ip, string port) { //접속시도 MemoryStream out_stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(out_stream); clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)); clientSocket.Connect(ie); if (clientSocket.Connected) { System.Threading.Thread t1 = new System.Threading.Thread (delegate() { JoinForReceive(clientSocket); }); t1.Start(); writer.Write(IPAddress.HostToNetworkOrder((int)CLIENT_MESSAGE.REQ_JOIN)); writer.Write(id); writer.Write(pw); writer.Write(mail); writer.Flush(); clientSocket.Send(out_stream.ToArray()); } else { MessageBox.Show("서버에 접속을 실패하였습니다. 서버가 열려있지 않거나 아이피, 포트번호에 이상이 있습니다."); } writer.Flush(); writer.Close(); writer.Dispose(); out_stream.Close(); out_stream.Dispose(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ServicePointManager.DefaultConnectionLimit = 500; if (ConfigurationManager.AppSettings["IsNode"] == "1") { SearchApi.Init(); } else { string log_db_path = @"C:\Users\Administrator\Documents\stackoverflow\LOG"; logdb = new Db(log_db_path); } ThreadPool.SetMinThreads(500, 500); _recent_clean_job = new System.Threading.Thread(f => { while (true) { try { Thread.Sleep(60000); _recent_data = new System.Collections.Concurrent.ConcurrentDictionary <string, DateTime>(); } catch (Exception ex) { LogError("ERROR IN CLEANING THREAD " + DateTime.Now + " \n" + ex.Message + " \n" + ex.StackTrace, ex); } } }); }
/// <summary> /// Initializes the static members of the ClientMarketData class. /// </summary> static ClientMarketData() { // The 'rowVersion' keeps track of the 'age' of the data model. It's the primary method to synchronize the client with // the server. The 'timeStamp' value gives an absolute reference to the 'rowVersion' value. That is, each time the // server resets, the rowVersions begin counting again. The 'timeStamp' from the server tells us if we can compare the // 'rowVersion's. If the timstamp between the server and the client are different, then we have to re-synchronize the // client and the server. ClientMarketData.rowVersion = 0; ClientMarketData.timeStamp = DateTime.MinValue; // These events are used to refresh the data model in the background and to enable synchronous refreshes of the // data model on request. ClientMarketData.refreshEvent = new AutoResetEvent(false); ClientMarketData.startDrawEvent = new AutoResetEvent(false); ClientMarketData.endDrawEvent = new AutoResetEvent(false); // This mutex is to insure that only one thread access the data model refresh at a time. ClientMarketData.refreshMutex = new Mutex(false); ClientMarketData.mergedRows = new ArrayList(); foreach (Table table in ClientMarketData.Tables) { table.RowChanged += new DataRowChangeEventHandler(RowChangedEvent); table.RowDeleted += new DataRowChangeEventHandler(RowChangedEvent); } // This thread is used to access the database for the objects that this user has access to. The end product of this // thread is a tree structure that contains the hierarchy of objects (accounts, users, trading desks, securities, etc.) // that the user can navigate. The results are passed back to this thread through the delegate procedure 'objectNode' // after the control window is created. threadBackground = new Thread(new ThreadStart(ThreadBackground)); threadBackground.IsBackground = true; threadBackground.Priority = System.Threading.ThreadPriority.Lowest; threadBackground.Name = "ClientMarketData Background"; threadBackground.Start(); }