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)); }
static void Main(string[] args) { const int THREADS = 5; var size = input.Count; List <System.Threading.Thread> threads = new List <System.Threading.Thread>(); for (int i = 0; i < THREADS; ++i) { var par = new Parameters(); double delta = (input.Count * 1.0) / THREADS; par.begin = Convert.ToInt32(i * delta); par.end = Convert.ToInt32((i + 1) * delta); var thread = new System.Threading.Thread(func); threads.Add(thread); thread.Start(par); } foreach (var thread in threads) { thread.Join(); } Console.WriteLine("Result:{0}", result); int res = input.Sum(it => it); Console.WriteLine("Result2:{0}", res); Console.ReadLine(); }
public void NoteMapGlue_AssignNoteBBC() { bool result = true; System.Threading.Thread t = new System.Threading.Thread(() => { MetaModel.MetaModel.Initialize(); var persistence = new PersistenceManager(); var noteEditor = new NoteEditor(); var form = CreateForm(); form.Controls.Add(noteEditor); form.Shown += (sender, args) => { var tree = persistence.OpenTree(@"Resources\Websites.mm"); var sut = new NoteMapGlue(noteEditor, persistence); tree.Tree.RootNode.FirstChild.Selected = true; result = noteEditor.HTML != null && noteEditor.HTML.Contains("BBC"); form.Close(); }; form.ShowDialog(); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsTrue(result); }
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 PerformanceCounterTest() { var stop = false; var t = new Thread( () => { while (!stop) { } }); t.Start(); for (int i = 0; i < 60; i++) { if ((i+1) % 10 == 0) { stop = !stop; } var value = 0;// PerformanceMonitor.GetProcessorTimeCounterValue(); Debug.WriteLine(value); } stop = true; t.Join(); }
private int RunInNewThread () { Thread th = new Thread(new ThreadStart(NewThreadRunner)); th.SetApartmentState(m_apt); th.Start(); th.Join(); return m_runResult; }
public void DifferentThreads_DifferentObjects_BuildUpInterfaceWithManyInterfaceDependencyProperties_Success() { var c = new Container(); c.RegisterType<IEmptyClass, EmptyClass>().AsPerThread(); c.RegisterType<ISampleClassWithInterfaceAsParameter, SampleClassWithInterfaceAsParameter>().AsPerThread(); c.RegisterType<ISampleClassWithManyInterfaceDependencyProperties, SampleClassWithManyInterfaceDependencyProperties>(); ISampleClassWithManyInterfaceDependencyProperties sampleClass1 = null; ISampleClassWithManyInterfaceDependencyProperties sampleClass2 = null; var thread1 = new Thread(() => { sampleClass1 = c.Resolve<ISampleClassWithManyInterfaceDependencyProperties>(ResolveKind.PartialEmitFunction); }); thread1.Start(); thread1.Join(); var thread2 = new Thread(() => { sampleClass2 = c.Resolve<ISampleClassWithManyInterfaceDependencyProperties>(ResolveKind.PartialEmitFunction); }); thread2.Start(); thread2.Join(); Assert.IsNotNull(sampleClass1.EmptyClass); Assert.IsNotNull(sampleClass1.SampleClass); Assert.IsNotNull(sampleClass2.EmptyClass); Assert.IsNotNull(sampleClass2.SampleClass); Assert.AreNotEqual(sampleClass1, sampleClass2); Assert.AreNotEqual(sampleClass1.EmptyClass, sampleClass2.EmptyClass); Assert.AreNotEqual(sampleClass1.SampleClass, sampleClass2.SampleClass); }
public static void SetClipboard(string result) { var thread = new Thread(() => Clipboard.SetText(result)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); }
public void DifferentThreads_DifferentObjects_RegisterClassWithDependencyPropertyAndDependencyMethodWithDifferentTypes_Success() { var c = new Container(); c.RegisterType<EmptyClass>().AsPerThread(); c.RegisterType<SampleClass>().AsPerThread(); c.RegisterType<SampleClassWithClassDependencyPropertyAndDependencyMethodWithDifferentTypes>(); SampleClassWithClassDependencyPropertyAndDependencyMethodWithDifferentTypes sampleClass1 = null; SampleClassWithClassDependencyPropertyAndDependencyMethodWithDifferentTypes sampleClass2 = null; var thread1 = new Thread(() => { sampleClass1 = c.Resolve<SampleClassWithClassDependencyPropertyAndDependencyMethodWithDifferentTypes>(ResolveKind.PartialEmitFunction); }); thread1.Start(); thread1.Join(); var thread2 = new Thread(() => { sampleClass2 = c.Resolve<SampleClassWithClassDependencyPropertyAndDependencyMethodWithDifferentTypes>(ResolveKind.PartialEmitFunction); }); thread2.Start(); thread2.Join(); Assert.IsNotNull(sampleClass1.SampleClass); Assert.IsNotNull(sampleClass1.EmptyClass); Assert.AreNotEqual(sampleClass1.SampleClass, sampleClass1.EmptyClass); Assert.AreEqual(sampleClass1.SampleClass.EmptyClass, sampleClass1.EmptyClass); Assert.IsNotNull(sampleClass2.SampleClass); Assert.IsNotNull(sampleClass2.EmptyClass); Assert.AreNotEqual(sampleClass2.SampleClass, sampleClass2.EmptyClass); Assert.AreEqual(sampleClass2.SampleClass.EmptyClass, sampleClass2.EmptyClass); Assert.AreNotEqual(sampleClass1, sampleClass2); Assert.AreNotEqual(sampleClass1.SampleClass, sampleClass2.SampleClass); Assert.AreNotEqual(sampleClass1.EmptyClass, sampleClass2.EmptyClass); }
public void DifferentThreads_DifferentObjects_RegisterInterfaceWithDependencyPropertyAndDependencyMethod_Success() { var c = new Container(); c.RegisterType<IEmptyClass, EmptyClass>().AsPerThread(); c.RegisterType<ISampleClassWithInterfaceDependencyPropertyAndDependencyMethodWithSameType, SampleClassWithInterfaceDependencyPropertyAndDependencyMethodWithSameType>(); ISampleClassWithInterfaceDependencyPropertyAndDependencyMethodWithSameType sampleClass1 = null; ISampleClassWithInterfaceDependencyPropertyAndDependencyMethodWithSameType sampleClass2 = null; var thread1 = new Thread(() => { sampleClass1 = c.Resolve<ISampleClassWithInterfaceDependencyPropertyAndDependencyMethodWithSameType>(ResolveKind.PartialEmitFunction); }); thread1.Start(); thread1.Join(); var thread2 = new Thread(() => { sampleClass2 = c.Resolve<ISampleClassWithInterfaceDependencyPropertyAndDependencyMethodWithSameType>(ResolveKind.PartialEmitFunction); }); thread2.Start(); thread2.Join(); Assert.IsNotNull(sampleClass1.EmptyClassFromDependencyProperty); Assert.IsNotNull(sampleClass1.EmptyClassFromDependencyMethod); Assert.AreEqual(sampleClass1.EmptyClassFromDependencyProperty, sampleClass1.EmptyClassFromDependencyMethod); Assert.IsNotNull(sampleClass2.EmptyClassFromDependencyProperty); Assert.IsNotNull(sampleClass2.EmptyClassFromDependencyMethod); Assert.AreEqual(sampleClass2.EmptyClassFromDependencyProperty, sampleClass2.EmptyClassFromDependencyMethod); Assert.AreNotEqual(sampleClass1, sampleClass2); Assert.AreNotEqual(sampleClass1.EmptyClassFromDependencyProperty, sampleClass2.EmptyClassFromDependencyProperty); Assert.AreNotEqual(sampleClass1.EmptyClassFromDependencyMethod, sampleClass2.EmptyClassFromDependencyMethod); }
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); }
static Program() { // Запускаем инициализацию в отдельном потоке var thread = new Thread(Initialize); thread.Start(); thread.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 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 void Send(string archiveFilename, CancellationToken cancellationToken, SimpleProgressCallback progressCallback = null) { // create drop effect memory stream byte[] moveEffect = new byte[] { (byte) (performCut ? 2 : 5), 0, 0, 0 }; MemoryStream dropEffect = new MemoryStream(); dropEffect.Write(moveEffect, 0, moveEffect.Length); // create file data object DataObject data = new DataObject(); data.SetFileDropList(new StringCollection { archiveFilename }); data.SetData("Preferred DropEffect", dropEffect); // create STA thread that'll work with Clipboard object Thread copyStaThread = new Thread(() => { Clipboard.Clear(); Clipboard.SetDataObject(data, true); }) { Name = "Clipboard copy thread" }; copyStaThread.SetApartmentState(ApartmentState.STA); // start the thread and wait for it to finish copyStaThread.Start(); copyStaThread.Join(); }
/// <summary> /// The run main window. /// </summary> //[Test] public void RunMainWindow() { var t = new Thread(this.CreateMainIssueWindow); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); }
/// <summary> /// Quickly open a sqlconnection and if it doesn't respond in the timeout time, throw a ConnectionError with the errorMessage /// </summary> /// <param name="conn">The sqlconnection that you are about to connect to</param> /// <param name="timeout">The timeout time in ms</param> /// <param name="errorMessage">The errormessage that the ConnectionException will have</param> public static void QuickOpen(this SqlConnection conn, int timeout = 5000, string errorMessage = "Timed out while trying to connect.") { // We'll use a Stopwatch here for simplicity. A comparison to a stored DateTime.Now value could also be used Stopwatch sw = new Stopwatch(); bool connectSuccess = false; // Try to open the connection, if anything goes wrong, make sure we set connectSuccess = false Thread t = new Thread(delegate() { try { sw.Start(); conn.Open(); connectSuccess = true; } catch { } }); // Make sure it's marked as a background thread so it'll get cleaned up automatically t.IsBackground = true; t.Start(); // Keep trying to join the thread until we either succeed or the timeout value has been exceeded while (timeout > sw.ElapsedMilliseconds) if (t.Join(1)) break; // If we didn't connect successfully, throw an exception if (!connectSuccess) throw new ConnectionException(errorMessage); }
public TypedData Process(TypedData data, IMutableProgressTracker progress, CancellationToken cancelToken) { progress.Status = "Taking a crop shot"; CropShotWindow cropShotWindow = null; var thread = new Thread(() => { cropShotWindow = new CropShotWindow { SourceImage = (Image) data.Data, DataName = data.Name }; cropShotWindow.ShowDialog(); }); // UI objects want to be in STA; make sure we're in STA thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); if (cropShotWindow.Data == null) { throw new CommandCanceledException(this); } progress.Progress = 1; return cropShotWindow.Data; }
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 void CreateShaderProgramSequential() { using (var thread0Window = Device.CreateWindow(1, 1)) using (var thread1Window = Device.CreateWindow(1, 1)) using (var window = Device.CreateWindow(1, 1)) using (ShaderProgramFactory factory0 = new ShaderProgramFactory(thread0Window.Context, ShaderSources.PassThroughVertexShader(), ShaderSources.PassThroughFragmentShader())) using (ShaderProgramFactory factory1 = new ShaderProgramFactory(thread1Window.Context, ShaderSources.PassThroughVertexShader(), ShaderSources.PassThroughFragmentShader())) { Thread t0 = new Thread(factory0.Create); t0.Start(); t0.Join(); Thread t1 = new Thread(factory1.Create); t1.Start(); t1.Join(); using (Framebuffer framebuffer = TestUtility.CreateFramebuffer(window.Context)) using (VertexArray va = TestUtility.CreateVertexArray(window.Context, factory0.ShaderProgram.VertexAttributes["position"].Location)) { window.Context.Framebuffer = framebuffer; window.Context.Draw(PrimitiveType.Points, 0, 1, new DrawState(TestUtility.CreateRenderStateWithoutDepthTest(), factory0.ShaderProgram, va), new SceneState()); TestUtility.ValidateColor(framebuffer.ColorAttachments[0], 255, 0, 0); window.Context.Clear(new ClearState()); window.Context.Draw(PrimitiveType.Points, 0, 1, new DrawState(TestUtility.CreateRenderStateWithoutDepthTest(), factory1.ShaderProgram, va), new SceneState()); TestUtility.ValidateColor(framebuffer.ColorAttachments[0], 255, 0, 0); } } }
public void ShouldNotThrowAnyExceptionsWhenCreatingIssuesWindow() { var t = new Thread(this.CreateMainIssueWindow); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); }
public void InterfaceReRegisteredFromClassToInstance_Success() { var c = new Container(); IEmptyClass emptyClass = new EmptyClass(); c.RegisterType<IEmptyClass, EmptyClass>().AsPerThread(); IEmptyClass emptyClass1 = null; IEmptyClass emptyClass2 = null; IEmptyClass emptyClass3 = null; IEmptyClass emptyClass4 = null; var thread = new Thread(() => { emptyClass1 = c.Resolve<IEmptyClass>(ResolveKind.FullEmitFunction); emptyClass2 = c.Resolve<IEmptyClass>(ResolveKind.FullEmitFunction); c.RegisterInstance(emptyClass).AsPerThread(); emptyClass3 = c.Resolve<IEmptyClass>(ResolveKind.FullEmitFunction); emptyClass4 = c.Resolve<IEmptyClass>(ResolveKind.FullEmitFunction); }); thread.Start(); thread.Join(); Assert.AreEqual(emptyClass1, emptyClass2); Assert.AreEqual(emptyClass, emptyClass3); Assert.AreEqual(emptyClass3, emptyClass4); Assert.AreNotEqual(emptyClass1, emptyClass3); }
public void TestConcurrency() { string customerId = null; using (MySqlContext context = LocalServiceLocator.GetService<IDbContextFactory>().CreateContext<MySqlContext>()) { context.Customers.Each(e => context.Customers.Remove(e)); context.SaveChanges(); } using (MySqlContext context = LocalServiceLocator.GetService<IDbContextFactory>().CreateContext<MySqlContext>()) { Customer c = new Customer(); c.FirstName = "James"; c.LastName = "Chan"; context.Customers.Add(c); context.SaveChanges(); customerId = c.Id; } var th1 = new Thread(() => { int n = 0; do { using (MySqlContext context = LocalServiceLocator.GetService<IDbContextFactory>().CreateContext<MySqlContext>()) { Customer c = context.Customers.Find(customerId); if (c != null) { c.FirstName = "Alex"; context.SaveChanges(); } } n++; } while (n < 2); }); th1.Start(); var th2 = new Thread(() => { int n = 0; do { using (MySqlContext context = LocalServiceLocator.GetService<IDbContextFactory>().CreateContext<MySqlContext>()) { Customer c = context.Customers.Find(customerId); if (c != null) { c.FirstName = "Jhon"; context.SaveChanges(); } } n++; } while (n < 2); }); th2.Start(); th1.Join(); th2.Join(); }
public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 10.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); }
public void Execute() { // // .NET 4.0より、Threadクラスに以下のメソッドが追加された。 // ・Yieldメソッド // // Yieldメソッドは、別のスレッドにタイムスライスを引き渡す為のメソッド。 // 今までは、Thread.Sleepを利用したりして、タイムスライスを切り替えるよう // にしていたが、今後はこのメソッドを利用することが推奨される。 // // 戻り値は、タイムスライスの引き渡しが成功したか否かが返ってくる。 // // // テスト用にスレッドを2つ起動する. // var t1 = new Thread(ThreadProc); var t2 = new Thread(ThreadProc); t1.Start("T1"); t2.Start("T2"); t1.Join(); t2.Join(); }
public void ShouldRemoveExecutionContextInstanceOnly() { var instance1 = new TestClass(); var instance2 = new TestClass(); var container = new Container(); container.Inject<TestInterface>(instance1, Lifecycle.HttpContextOrExecutionContextLocal); TestInterface[] thread2ResolvedTestClasses = null; bool thread2HasRegistration = true; ExecutionContext.SuppressFlow(); var thread2 = new Thread(() => { container.Inject<TestInterface>(instance2, Lifecycle.HttpContextOrExecutionContextLocal); thread2ResolvedTestClasses = container.ResolveAll<TestInterface>().ToArray(); container.RemoveInstancesOf<TestInterface>(Lifecycle.HttpContextOrExecutionContextLocal); thread2HasRegistration = container.HasRegistrationFor<TestInterface>(); }); thread2.Start(); thread2.Join(1000); ExecutionContext.RestoreFlow(); Assert.IsFalse(thread2HasRegistration); Assert.AreEqual(1, thread2ResolvedTestClasses.Length); Assert.AreEqual(instance1, container.Resolve<TestInterface>()); }
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(); } }
public void CanEnumerateSafely() { var strings = LangTestHelpers.RandomStrings(1000, 50); var results = new ConcurrentQueue<string>(); using (var stringsEnumerator = strings.GetEnumerator()) { var tse = new ThreadSafeEnumerator<string>(stringsEnumerator); var threads = new List<Thread>(); for (var i = 0; i < 10; i++) { var thread = new Thread(() => { string it = null; while (tse.TryGetNext(ref it)) { results.Enqueue(it); } }); thread.Start(); threads.Add(thread); } foreach (var thread in threads) { thread.Join(); } } CollectionAssert.AreEquivalent(strings, results); }
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 DifferentThreads_DifferentObjects_RegisterClassWithDependencyPropertyAndDependencyMethod_Success() { var c = new Container(); c.RegisterType<EmptyClass>().AsPerThread(); var sampleClass1 = new SampleClassWithClassDependencyPropertyAndDependencyMethodWithSameType(); var sampleClass2 = new SampleClassWithClassDependencyPropertyAndDependencyMethodWithSameType(); var thread1 = new Thread(() => { c.BuildUp(sampleClass1, ResolveKind.PartialEmitFunction); }); thread1.Start(); thread1.Join(); var thread2 = new Thread(() => { c.BuildUp(sampleClass2, ResolveKind.PartialEmitFunction); }); thread2.Start(); thread2.Join(); Assert.IsNotNull(sampleClass1.EmptyClassFromDependencyProperty); Assert.IsNotNull(sampleClass1.EmptyClassFromDependencyMethod); Assert.AreEqual(sampleClass1.EmptyClassFromDependencyProperty, sampleClass1.EmptyClassFromDependencyMethod); Assert.IsNotNull(sampleClass2.EmptyClassFromDependencyProperty); Assert.IsNotNull(sampleClass2.EmptyClassFromDependencyMethod); Assert.AreEqual(sampleClass2.EmptyClassFromDependencyProperty, sampleClass2.EmptyClassFromDependencyMethod); Assert.AreNotEqual(sampleClass1, sampleClass2); Assert.AreNotEqual(sampleClass1.EmptyClassFromDependencyProperty, sampleClass2.EmptyClassFromDependencyMethod); Assert.AreNotEqual(sampleClass1.EmptyClassFromDependencyMethod, sampleClass2.EmptyClassFromDependencyMethod); }
/// <summary> /// The test plugins option window. /// </summary> public void TestPluginsOptionWindow() { var t = new Thread(this.Threadprc); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); }
public void JoinThread() { if (thread == null) { throw new UnityException("thread not created yet"); } thread.Join(); }
// SOCKET FUNCTIONS // void StartServer() { UnityEngine.Debug.Log("Starting server..."); socketThread = new System.Threading.Thread(NetworkCode); socketThread.IsBackground = true; socketThread.Start(); socketThread.Join(); }
public virtual void Abort() { IsDone = true; if (m_Thread != null) { m_Thread.Abort(); m_Thread.Join(); m_Thread = null; } }
void OnDisable() { StopCoroutine(coGarbageCollection); coGarbageCollection = null; if (thread != null) { exit = true; jobEvent.Set(); thread.Join(); thread = null; } }
public LinkedList <Vector3> GetPath(Vector3 from, Vector3 to) { MapGenerator.Coord start = mapGen.WorldToCoordPoint(from); MapGenerator.Coord end = mapGen.WorldToCoordPoint(to); Node startNode = nodeMap[start.tileX, start.tileY]; Node endNode = nodeMap[end.tileX, end.tileY]; LinkedList <Vector3> path = null; System.Threading.Thread newThread = new System.Threading.Thread(() => path = startNode.FindPathTo(endNode)); newThread.Start(); newThread.Join(); return(path); }
public void TestKeylogger() { string results = ""; Threads.Thread t = new Threads.Thread(() => { results = Keylogger.StartKeylogger(3); }); t.Start(); Forms.SendKeys.SendWait("test123"); t.Join(3000); Assert.IsTrue(results.Length > 0); Assert.IsTrue(results.Contains("test123")); }
/// <summary> /// Stop Scanning /// </summary> public void StopScan() { if (this._isScanning) { //Avoid thread lock with main thread/gui Thread myThread = new System.Threading.Thread(delegate() { this._isScanning = false; _scanThread.Join(); this.SendCommand(Commands.RPLIDAR_CMD_STOP); }); myThread.Start(); myThread.Join(); return; } }
public static DialogResult STAShowDialog(FileDialog dialog) { DialogState state = new DialogState(); state.dialog = dialog; System.Threading.Thread t = new System.Threading.Thread(state.ThreadProcShowDialog); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); return(state.result); }
public void TestMultiTreadedEvaluate() { System.Threading.Thread t1 = new System.Threading.Thread(ThreadRunEvaluate); t1.Name = "Thread1"; System.Threading.Thread t2 = new System.Threading.Thread(ThreadRunEvaluate); t2.Name = "Thread2"; var e = new DynamicExpression("1+1*200", ExpressionLanguage.Flee); t1.Start(e); t2.Start(e); t1.Join(); t2.Join(); }
void OnDisable() { if (thread != null) { stop = true; Thread.Sleep(5); thread.Join(); thread = null; } if (pp != null) { pp.Dispose(); pp = null; } }
private void LoginStep1() { try { Options.GlobalVar.IAUsername = this.cbLoginName.Text.Trim(); Options.GlobalVar.IAPassword = this.txtPassword.Text.Trim(); if (string.IsNullOrEmpty(Options.GlobalVar.IAUsername) || string.IsNullOrEmpty(Options.GlobalVar.IAPassword)) { throw new Exception("用户名或者密码不能为空!"); } System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(LoginIA)); th.Start(); if (!th.Join(System.Threading.Timeout.Infinite))//此处被Abort { th.Abort(); throw new TimeoutException("连接超时,请稍后再试!"); } else if (!string.IsNullOrEmpty(this.errorMsg)) { throw new Exception(this.errorMsg); } if (Options.GlobalVar.QueryType == XMLConfig.QueryType.Eterm) { th = new System.Threading.Thread(new System.Threading.ThreadStart(LoginStep2)); th.Start(); } else { this.DialogResult = DialogResult.OK; } } catch (ThreadAbortException) { Stop(); } catch (Exception ex) { this.BeginInvoke(new MethodInvoker(delegate { MessageBox.Show("登录失败:" + ex.Message); })); Stop(); } }
public double EvaluateNetwork(INetwork network) { INetwork tempNet = null; NeatGenome.NeatGenome tempGenome = null; tempGenome = substrate.generateGenome(network); tempNet = tempGenome.Decode(null); SharpNeatExperiments.Pacman.MyForm1.neatGenome = tempGenome; SharpNeatExperiments.Pacman.MyForm1.network = tempNet; SharpNeatExperiments.Pacman.MyForm1.InitStartLine(); double retries = 1; double totalFitness = 0; for (int i = 0; i < retries; i++) { var simplePacmanController = new PacmanAINeural.SPSUPGController(); simplePacmanController.SetBrain(tempNet, false, tempGenome, network, substrate.getSUPGMap()); simplePacmanController.Substrate = substrate; SharpNeatExperiments.Pacman.SimplePacman simplePacman = null; Thread visualizerThread; visualizerThread = new System.Threading.Thread(delegate() { bool fastNoDraw = true; simplePacman = new SharpNeatExperiments.Pacman.SimplePacman(simplePacmanController, fastNoDraw, new Random(i)); if (!fastNoDraw) { System.Windows.Forms.Application.Run(simplePacman); } }); visualizerThread.Start(); visualizerThread.Join(); totalFitness += simplePacman.returnGameScore;// visualizer.returnGameState; } double avgFitness = totalFitness / retries; return(avgFitness); /*int time = visualizer.returnGameState; * return (double)time;//fitness;*/ }
public bool Stop(out string error) { error = null; var stopThread = new System.Threading.Thread(() => { string threadError = null; while (ChunkInsertQueue.Count > 0 || BlockInsertOrUpdateQueue.Count > 0) { Update(out threadError); } }); stopThread.Start(); stopThread.Join(); return(true); }
public void CloseThreadedSocket(bool WaitForThread = true) { this.IsRunning = false; // kill thread if (RecvThread != null) { Debug.Log("aborting thread..."); // I think we can safely abort, might need to check. If we don't, depending on how much data we've thrown at the decoder, this could take ages to finish RecvThread.Abort(); RecvThread.Join(); RecvThread = null; } // stop thread looping this.IsRunning = false; }
void OnDisable() { lock (m_ThreadJobs) { // ask thread to exit isClosing = true; if (m_Heap != null && m_Heap.isProcessing) { m_Heap.abortActiveStepRequested = true; } Monitor.Pulse(m_ThreadJobs); } m_Thread.Join(); // wait for thread exit m_Thread = null; DestroyViews(); }
public void NoteMapGlue() { NoteMapGlue sut = null; System.Threading.Thread t = new System.Threading.Thread(() => { MetaModel.MetaModel.Initialize(); var persistence = new PersistenceManager(); var nodeEditor = new NoteEditor(); sut = new NoteMapGlue(nodeEditor, persistence); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsNotNull(sut); }
public static void WaitForStopThread() { try { if (!robotThread.Join(1000)) { LoggerN.logError("Unable to stop thread for " + statics.getName()); robotPeer.punishBadBehavior(BadBehavior.UNSTOPPABLE); robotPeer.setRunning(false); } } catch (Exception ex) { LoggerN.logError(ex); throw; } }
public void TestThreadFormsInit() { Sys_Threading.Thread thread; thread = new Sys_Threading.Thread(new ThreadStart(GuiThread)); thread.Start(); thread.Join(); try { GuiThread(); } catch (Exception e) { Assert.Fail("#1"); } }
// private void getData() { this.Dispatcher.Invoke(() => { DBAccess matchResults = new DBAccess(); System.Threading.Thread findPatterns = new System.Threading.Thread(matchResults.Begin); try { //find patterns between data sets provided by user matchResults.FindPatterns(this.text1, this.text2, this.myDataGrid, this.myDataGrid2); } catch (Exception ex) { textBox3.Text = textBox3.Text + "\r\n" + "\r\n" + Convert.ToDateTime(DateTime.Now.ToString("dd-MMM-yyyy")) + "\r\n" + "-------------------------------" + "\r\n" + ex; return; } findPatterns.Start(); Stats stats = matchResults.Stats; this.SetStats(stats); myDataGrid.UpdateLayout(); myDataGrid2.UpdateLayout(); //Find patterns between data sets and code if (String.Equals(pathTextBox.Text, "Path") == false) { if (String.Equals(pathTextBox.Text, " ") == false) { if (pathTextBox.Text != null) { CodeSearcher codeSearch = new CodeSearcher(); System.Threading.Thread searchCodeThread = new System.Threading.Thread(codeSearch.searchCode); codeSearch.directory = pathTextBox.Text; searchCodeThread.Start(); searchCodeThread.Join(); foreach (String line in codeSearch.filenames) { textBox4.Text = textBox4.Text + line; } } } } }); }
public void Stop() { //stopRequested = true; // resetEventPOP.Set(); workThreadSMSProcess.Join(); isRunning = false; try { objSMS.Disconnect(); } catch (Exception ex) { Trace.WriteLine(ex.Message); } stopRequested = false; }
/// <summary> /// Returns the binary data of the image in the specifed format. /// </summary> /// <param name="format">The format of the bitmap image specified as "gif", "jpg", "png", "bmp", "jxr" or "tiff".</param> public byte[] ToByteArray(string format) { //if image not altered return orig data if (_data != null) { return(_data); } //placed in a thread set to STA to overcome 0xC0000005 thrown in encoder.Save if (!String.IsNullOrEmpty(Copyright)) { byte[] data = null; System.Threading.Thread worker = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(delegate(object obj) { BitmapEncoder encoder = GetEncoder(format); try { BitmapMetadata meta = new BitmapMetadata(format); meta.Copyright = Copyright; encoder.Frames.Insert(0, BitmapFrame.Create(_source, null, meta, null)); //using insert because we're getting error about IList not containing Add method using (MemoryStream memoryStream = new MemoryStream()) { encoder.Save(memoryStream); data = memoryStream.ToArray(); } } catch (NotSupportedException) { } //specified format does not support copyright metadata })); worker.SetApartmentState(System.Threading.ApartmentState.STA); worker.Start(); worker.Join(); if (data != null) { return(data); } } BitmapEncoder targetEncoder = GetEncoder(format); targetEncoder.Frames.Add(BitmapFrame.Create(_source)); using (MemoryStream memoryStream = new MemoryStream()) { targetEncoder.Save(memoryStream); return(memoryStream.ToArray()); } }
public static bool Ping(string hostNameOrAddress, int timeout, out Exception error) { Console.Write(" Ping... "); var success = false; error = null; var sw = new System.Diagnostics.Stopwatch(); sw.Start(); PingReply reply = null; Exception replyError = null; // Use proper threading, because other asynchronous classes // like "Tasks" have problems with Ping. var ts = new System.Threading.ThreadStart(delegate() { var ping = new Ping(); try { reply = ping.Send(hostNameOrAddress); } catch (Exception ex) { replyError = ex; } ping.Dispose(); }); var t = new System.Threading.Thread(ts); t.Start(); t.Join(timeout); if (reply != null) { success = (reply.Status == IPStatus.Success); } else if (replyError != null) { error = replyError; } else { error = new Exception("Ping timed out (" + timeout.ToString() + "): " + sw.Elapsed.ToString()); } Console.WriteLine("{0} {1}", success, error); return(success); }
protected void Done(object sender, EventArgs e) { // Collect info about players Scrabble.Game.InitialConfig.players = new Player.Player[numberOfPlayers]; for (int i = 0; i < numberOfPlayers; i++) { if (CPUchecks[i].Active) { Scrabble.Game.InitialConfig.players[i] = new Scrabble.Player.ComputerPlayer(entryes[i].Text, new Player.standartAI()); continue; } if (MPchecks[i].Active) { Scrabble.Game.InitialConfig.players[i] = new Scrabble.Player.NetworkPlayer(entryes[i].Text, IPs[i].Text); continue; } Scrabble.Game.InitialConfig.players[i] = new Scrabble.Player.Player(entryes[i].Text); } // OPEN LOGS #if DEBUG if (Scrabble.Game.InitialConfig.log) { Scrabble.Game.InitialConfig.logStreamAI = new StreamWriter("./lastAI.log", false); } #endif // WAIT FOR DICTIONARY LOAD tdic.Join(); lock ( dicLoc ) { Scrabble.Game.InitialConfig.dictionary = this.dic; } // ALL DONE Scrabble.Game.InitialConfig.game = new Scrabble.Game.Game(false); if (Scrabble.Game.InitialConfig.log) { Console.Out.WriteLine("[INFO]\tNastavení parametrů dokončeno."); } this.HideAll(); Gtk.Application.Quit(); }
protected override void Dispose(bool disposing) { if (!disposed) { disposed = true; GameInstance.Components.Remove(this); if (ownsServices) { GameInstance.Components.Remove(services); services.Dispose(); } todo.Set(); thread.Join(); todo.Close(); thread = null; todo = null; } }
public void Stop() { FpsDisplayer.Enabled = false; queueThread.Abort(); queueThread.Join(); queueThread = null; writeThread.Abort(); writeThread.Join(); writeThread = null; webcam.SignalToStop(); webcam.WaitForStop(); splitter.Stop(); writingQueue.Clear(); }
public void Dispose() { // stop thread before killing decoder InputQueue = null; if (InputThread != null) { // I think we can safely abort, might need to check. If we don't, depending on how much data we've thrown at the decoder, this could take ages to finish InputThread.Abort(); InputThread.Join(); InputThread = null; } if (Instance.HasValue) { PopH264_DestroyInstance(Instance.Value); } Instance = null; }
public static void RunTests(TestRunMode testMode) { UnityEngine.Debug.Log("Started running test"); System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); System.Reflection.Assembly assembly = assemblies.FirstOrDefault(assemblyName => assemblyName.GetName().Name.Equals("Assembly-CSharp-Editor")); var filters = AddTestToBeRun(testMode); NUnit.Framework.Interfaces.ITestListener listener = new TestRunListener(CallRunDelegate); var testAssemblyRunner = new NUnit.Framework.Api.NUnitTestAssemblyRunner(new NUnit.Framework.Api.DefaultTestAssemblyBuilder()); testAssemblyRunner.Load(assembly, new System.Collections.Generic.Dictionary <string, object>()); progress = 0; total = filters.Filters.Count; System.Threading.Thread runTestThread = new System.Threading.Thread(() => { var result = testAssemblyRunner.Run(listener, filters); SetTestStatus(result); AltUnityTesterEditor.isTestRunResultAvailable = true; AltUnityTesterEditor.selectedTest = -1; }); runTestThread.Start(); if (AltUnityTesterEditor.EditorConfiguration.platform != Platform.Editor) { float previousProgres = progress - 1; while (runTestThread.IsAlive) { if (previousProgres == progress) { continue; } UnityEditor.EditorUtility.DisplayProgressBar(progress == total ? "This may take a few seconds" : _testName, progress + "/" + total, progress / total); previousProgres = progress; } } runTestThread.Join(); if (AltUnityTesterEditor.EditorConfiguration.platform != Platform.Editor) { AltUnityTesterEditor.needsRepaiting = true; UnityEditor.EditorUtility.ClearProgressBar(); } }
/// <summary> /// Perform our remoting call with a forced timeout. /// </summary> /// <param name="method"></param> protected void PerformRemoting(ThreadStart method) { Exception remotingException = null; var thread = new System.Threading.Thread(delegate() { try { method(); } catch (Exception ex) { remotingException = ex; } }); thread.Start(); if (thread.Join(_remotingWaitTime)) { if (remotingException != null) { if (remotingException is PeachException) { throw new PeachException(remotingException.Message, remotingException); } if (remotingException is SoftException) { throw new SoftException(remotingException.Message, remotingException); } if (remotingException is RemotingException) { throw new RemotingException(remotingException.Message, remotingException); } throw new AgentException(remotingException.Message, remotingException); } } else { throw new RemotingException("Remoting call timed out."); } }
private void Play(int times, int tone) { for (int i = 1; i <= times; i++) { // System.Media.SystemSounds.Beep.Play(); //Console.Beep(); //new Thread(() => Console.Beep( 200+tone , 100 * (i * 10))).Start(); System.Threading.Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { Console.Beep(200 + tone, 100 * (i * 10)); } )); thread.Start(); thread.Join(); } }