Start() public method

public Start ( ) : void
return void
コード例 #1
0
ファイル: TcpServer.cs プロジェクト: johnmensen/TradeSharp
 public TcpServer(int port)
 {
     listener = new TcpListener(port);
     listenThread = new Thread(ListenThreadFun);
     listenThread.Start();
     encoder = new ASCIIEncoding();
 }
コード例 #2
0
        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);
        }
コード例 #3
0
 public void ResizingThreadTableWorks()
 {
     var defaultThreadTableSize = Environment.ProcessorCount;
     var threads = new List<WaitHandle>();
     var counter = new ReferenceCounter();
     var obj = new object();
     for (int threadNumber = 0; threadNumber < defaultThreadTableSize * 2; threadNumber++)
     {
         var thread = new Thread(new ThreadStart(() =>
         {
             var handle = new AutoResetEvent(false);
             threads.Add(handle);
             for (int itteration = 0; itteration < 100; itteration++)
             {
                 counter.AddReference(obj);
                 Thread.Sleep(10);
                 counter.Release(obj);
             }
             handle.Set();
         }));
         thread.Start();
     }
     WaitHandle.WaitAll(threads.ToArray());
     Assert.Equal(0, (int)counter.GetGlobalCount(0));
 }
コード例 #4
0
 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);
 }
コード例 #5
0
ファイル: Fixture.cs プロジェクト: boydlee/CefSharp
        public void SetUp()
        {
            var settings = new Settings();
            if (!CEF.Initialize(settings))
            {
                Assert.Fail();
            }

            var thread = new Thread(() =>
            {
                var form = new Form();
                form.Shown += (sender, e) =>
                {
                    Browser = new WebBrowser()
                    {
                        Parent = form,
                        Dock = DockStyle.Fill,
                    };

                    createdEvent.Set();
                };

                Application.Run(form);
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            createdEvent.WaitOne();
        }
コード例 #6
0
 public void StartBiddingIn(FakeAuctionServer auction)
 {
     var thread = new Thread(StartApplication);
     thread.Start();
     driver = new AuctionSniperDriver(1000, ApplicationName);
     driver.ShowsSniperStatus(StatusJoining);
 }
コード例 #7
0
ファイル: TcpServer.cs プロジェクト: johnmensen/TradeSharp
 public TcpServer(int port, Encoding enc)
 {
     listener = new TcpListener(port);
     listenThread = new Thread(ListenThreadFun);
     listenThread.Start();
     encoder = enc;
 }
コード例 #8
0
ファイル: TaskQueue.cs プロジェクト: arsaccol/SLED
 public void Start()
 {
     Stop();
     m_bThreadStop = false;
     m_thread = new System.Threading.Thread(Main);
     m_thread.Start();
 }
コード例 #9
0
        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));
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: isalento/XefFrameExtractor
        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();
            }
        }
コード例 #11
0
ファイル: mainForm.cs プロジェクト: Foltik/SugoiRC
 //UI Init and Main Thread Creation
 public mainForm()
 {
     InitializeComponent();
     AcceptButton = buttonSend;
     tmain = new System.Threading.Thread(main);
     tmain.Start();
 }
コード例 #12
0
        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);
                }
            }
        }
コード例 #13
0
ファイル: Setup.cs プロジェクト: GeroL/MOSA-Project
        /// <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();
        }
コード例 #14
0
 public static void SetClipboard(string result)
 {
     var thread = new Thread(() => Clipboard.SetText(result));
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
     thread.Join();
 }
コード例 #15
0
        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);
             }
        }
コード例 #16
0
ファイル: CallAsyncOpTests.cs プロジェクト: umabiel/WsdlUI
        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");
        }
コード例 #17
0
        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();
            }
        }
コード例 #18
0
ファイル: RelayPort.cs プロジェクト: mbaldini/NovaOS
 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();
 }
コード例 #19
0
        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");
        }
コード例 #20
0
 public static void StartService()
 {
     Thread thread = new Thread(OrderProcessingService.Run);
     thread.Name = "Order Processing Thread";
     thread.IsBackground = true;
     thread.Start();
 }
コード例 #21
0
        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);
        }
コード例 #22
0
 public static void Start(string logFolder)
 {
     _logFolder = logFolder;
     LogEntryFileWriter.LogFolder = _logFolder;
     Thread monitorThread = new Thread(new ThreadStart(Monitor));
     monitorThread.Start();
 }
コード例 #23
0
        // 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();
        }
コード例 #24
0
        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);
        }
コード例 #25
0
ファイル: MessageQueue.cs プロジェクト: Isszul/XNAplay
 public MessageQueue()
 {
     _running = true;
     _processMessageHandlers = new List<ProcessMessageHandler>();
     _messageQueueThread = new Thread(new ThreadStart(processQueue));
     _messageQueueThread.Start();
 }
コード例 #26
0
ファイル: MainActivity.cs プロジェクト: nubix-biz/OsmSharp
        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();
        }
コード例 #27
0
        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);
        }
コード例 #28
0
ファイル: CriticalPathMethod.cs プロジェクト: pourmand/amaal
 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");
 }
コード例 #29
0
ファイル: RelayPort.cs プロジェクト: mbaldini/NovaOS
 public RelayPort(Cpu.Pin pin, bool initialState, int timeout)
     : base(pin, initialState)
 {
     currentstate = initialState;
     relayThread = new Thread(new ThreadStart(RelayLoop));
     relayThread.Start();
 }
コード例 #30
0
        public void Run(System.Windows.Forms.IWin32Window wnd)
        {
            Thread thread = new Thread(DoWork);
            thread.Start();

            ShowDialog(wnd);
        }
コード例 #31
0
ファイル: Thread.cs プロジェクト: zhuzeyu22/robocode
 /// <summary>
 /// Causes a thread to be scheduled for execution.
 /// </summary>
 public void Start(object param)
 {
     thread.Start(param);
 }
コード例 #32
0
 public void Start()
 {
     _running = true;
     _thread.Start();
 }
コード例 #33
0
            /// <summary>
            /// Создание и запуск потоков для заполнения "чёкнутого" бокса
            /// </summary>
            /// <param name="x">номер панели</param>
            public void m_PanelGetDate_DelegateCheckPanel(int x)
            {
                var thread = new System.Threading.Thread(FillBox);

                thread.Start(x);
            }
コード例 #34
0
    // This method allows the user to log in and play (if login is successful). Automatically called by either connectToMainServer() or signup().
    public void loginAndPlay(int port)
    {
        // Check if user left either field blank.
        if (usernameLogin.text.Equals("") || passwordLogin.text.Equals(""))
        {
            loginErrorMessage.enabled = true;
            return;
        }

        // First, connect to the subserver at the given port.
        Socket cnxn         = null;
        bool   playerInGame = false;       // tracks whether the player is in-game (i.e. not in the main menu)

        try {
            cnxn = new Socket(ip, port);
            ObjectOutputStream output = new ObjectOutputStream(cnxn.getOutputStream());

            // Send handshake
            output.writeInt(handshake);
            output.flush();

            // Now that we have connected and sent our handshake, we can send commands.
            // First: log in.
            output.writeInt(LOGIN);
            output.flush();

            output.writeObject(usernameLogin.text);
            output.flush();

            output.writeObject(passwordLogin.text);
            output.flush();

            // Check if login was successful or failed
            ObjectInputStream input = new ObjectInputStream(cnxn.getInputStream());
            cnxn.setSoTimeout(10000);
            if (input.readInt() != SPU.ServerResponse.LOGIN_OK.ordinal())
            {
                // Login failed at this point. Disconnect from the server so the user can try again.
                loginErrorMessage.enabled = true;
                output.writeInt(DISCONNECT);
                output.flush();
                input.close();
                output.close();
                cnxn.close();
                return;
            }
            // At this point, login was successful.
            ((StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)))).saveLogin();
            loginErrorMessage.enabled = false;

            // Need to get the map first so the user can see stuff. First send the command, then receive the map and visibility.
            output.writeInt(GETCOND);
            output.flush();

            int          visibility = input.readInt();
            SPU.Tile[][] map        = (SPU.Tile[][])(input.readObject());

            // Load the game and start necessary threads.
            isLoading = true;
            StartCoroutine("LoadGame");
            while (isLoading)
            {
                ;
            }
            playerInGame = true;
            Destroy(GameObject.Find("Login Menu"));
            Destroy(GameObject.Find("Registration Menu"));
            Destroy(GameObject.Find("Main Menu Music"));

            // Create a thread to process user inputs (i.e. for the menu and for player movement)
            userInputThread = new System.Threading.Thread(new ThreadStart(new UserInputThread().ProcessInput));
            userInputThread.Start();
            while (!userInputThread.IsAlive)
            {
                ;                                         //loop until thread activates
            }
            // TO DO MUCH LATER: Draw the map, using visibility to determine visible tiles, and put this in the new scene.

            // At this point, process move commands one at a time (or logout if the user chooses).

            while (cmd != LOGOUT)
            {
                // First write the command...
                output.writeInt(cmd);
                output.flush();
                // ...then receive the updated visibility and map from the server.
                visibility = input.readInt();
                map        = (SPU.Tile[][])(input.readObject());
            }

            // At this point, user is ready to log out (cmd == LOGOUT).
            output.writeInt(LOGOUT);
            output.flush();

            // The game can just exit everything completely if the user is quitting to desktop.
            if (isQuitting)
            {
                Application.Quit();
            }

            input.close();
            output.close();
            cnxn.close();
            Destroy(GameObject.Find("BG Music"));
            isLoading = true;
            StartCoroutine("LoadMainMenu");
            while (isLoading)
            {
                ;
            }
            Destroy(this);
        }catch (java.lang.Exception e) {
            // Deal with a failed connection attempt
            StartMenuScript sms = (StartMenuScript)(startMenu.GetComponent(typeof(StartMenuScript)));
            if (cnxn == null)
            {
                sms.RaiseErrorWindow("Failed to connect. Check your connection settings. The subserver may be down.");
            }
            else if (e.GetType() == typeof(SocketTimeoutException) && !playerInGame)
            {
                sms.RaiseErrorWindow("Connection timed out. Check your connection. The subserver may have gone down.");
            }
            else
            {
                // Return to the main menu, since connection has timed out.
                Destroy(startMenu);
                Destroy(GameObject.Find("BG Music"));
                userInputThread.Abort();
                userInputThread.Join();
                isLoading = true;
                StartCoroutine("LoadMainMenu");
                while (isLoading)
                {
                    ;
                }
                StartMenuScript sms2 = ((StartMenuScript)(GameObject.Find("Start Menu").GetComponent <StartMenuScript>()));
                sms2.RaiseErrorWindow("Connection timed out. Check your connection. The subserver may have gone down.");
                Destroy(this);
            }
        }catch (System.Exception e) {
            // This handles C# exceptions. These shouldn't happen, which is why the errors are printed to the console (for us to test for ourselves).
            print("Encountered a C# exception:\n");
            print(e.StackTrace);
        }
    }
コード例 #35
0
        /// <summary>
        /// Init the CameraControl
        /// </summary>
        public IntermecCameraControl2()
        {
            InitializeComponent();

            //read res setting for snapshots and preview
            cameraRes  = (Camera.ImageResolutionType)ITCTools.registrySettings.cameraResolution;
            previewRes = (Camera.ImageResolutionType)ITCTools.registrySettings.previewResolution;

            //disable HW Trigger of Scanner
            YetAnotherHelperClass.setHWTrigger(false);
            try
            {
                if (IntermecCamera != null)
                {
                    addLog("Init() old IntermecCamera found. Disposing...");
                    // IntermecCamera.Streaming = false; //we dont switch streaming except once, ALL THE TIME
                    IntermecCamera.Dispose();
                    IntermecCamera = null;
                }
                else
                {
                    addLog("Init() Creating NEW IntermecCamera...");
                }

                //added to check for exception in creating a new Camera
                int iTry = 1; bool bSuccess = false; string sEx = "";
                do
                {
                    try
                    {
                        //using the same sequence as in sample CN3Camera
#if USE_LOW_RES
                        IntermecCamera = new Camera(CameraPreview, Camera.ImageResolutionType.Lowest);
#else
                        IntermecCamera = new Camera(CameraPreview, previewRes);// Camera.ImageResolutionType.Medium);
#endif
                        //IntermecCamera.PictureBoxUpdate = Camera.PictureBoxUpdateType.None;
                        IntermecCamera.PictureBoxUpdate = Camera.PictureBoxUpdateType.Fit; // None;// Fit;// AdjustToFrameSize;
                        bSuccess = true;
                        addLog("Init() IntermecCamera creation OK. Try " + iTry.ToString() + " of 3");
                    }
                    catch (Intermec.Multimedia.CameraException ex)
                    {
                        sEx = ex.Message;
                        addLog("Init() IntermecCamera creation failed. Try " + iTry.ToString() + " of 3 \nCameraException: \n" + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        sEx = ex.Message;
                        addLog("Init() IntermecCamera creation failed. Try " + iTry.ToString() + " of 3 \nException: \n" + ex.Message);
                    }
                    finally
                    {
                        GC.Collect();
                        iTry++;
                    }
                } while (iTry <= 3 && !bSuccess);
                if (IntermecCamera == null)
                {
                    throw new FileNotFoundException("IntermecCamera did not load. CnxDShow.cab installed?\nException: " + sEx);
                }

                // moving to end of INIT() does not fix problem with NO STREAM AT FIRST INIT()!
#if STREAMING_ON
                addLog("Init() 1 IntermecCamera.Streaming=true...");
                IntermecCamera.Streaming = true;   //we start with streaming = true ALL THE TIME
#else
                addLog("Init() 1 IntermecCamera.Streaming=true...");
                IntermecCamera.Streaming = true;   //we start with streaming = true ALL THE TIME
#endif
                #region AutoFlash
                try
                {
                    addLog("IntermecCamera testing Flash.Available...");
                    if (IntermecCamera.Features.Flash.Available)
                    {
                        addLog("IntermecCamera testing Flash.Available OK. Changing to Auto...");
                        if (IntermecCamera.Features.Flash.SupportsAutoMode)
                        {
                            addLog("IntermecCamera testing Flash.Available OK. Changed to Auto OK");
                            IntermecCamera.Features.Flash.Auto = true;
                        }
                        else
                        {
                            addLog("IntermecCamera testing Flash.Available OK. No AutoMode support");
                        }
                    }
                    else
                    {
                        addLog("IntermecCamera testing Flash.Available OK. No Flash support");
                    }
                }
                catch (Exception)
                {
                    addLog("IntermecCamera testing Flash throwed exception.");
                }
                #endregion
#if MYDEBUG
                //for DEBUG only
                System.Diagnostics.Debug.WriteLine("CurrentViewfinderResolution 1=" +
                                                   IntermecCamera.CurrentViewfinderResolution.Width.ToString() + "x" +
                                                   IntermecCamera.CurrentViewfinderResolution.Height.ToString());
#endif
                //System.Diagnostics.Debug.WriteLine("Current viewfinderRes 2=" +
                //    IntermecCamera.CurrentViewfinderResolution.Width.ToString() + "x" +
                //    IntermecCamera.CurrentViewfinderResolution.Height.ToString());

                //moved to end
                //######## IntermecCamera.SnapshotEvent += new SnapshotEventHandler(IntermecCamera_SnapshotEvent);

                //IntermecCamera.SnapshotFile.Filename = "FotoKamera_"+ DateTime.Now.ToShortDateString()+ "_" + DateTime.Now.ToShortTimeString() + ".jpg";
                IntermecCamera.SnapshotFile.ImageFormatType = Camera.ImageType.JPG;
                //WARNING, if you dont set this property, snapshot may fail with garbage image
#if USE_LOW_RES
                IntermecCamera.SnapshotFile.ImageResolution = Camera.ImageResolutionType.Lowest;
#else
                IntermecCamera.SnapshotFile.ImageResolution = cameraRes;// Camera.ImageResolutionType.Medium;
#endif
                IntermecCamera.SnapshotFile.JPGQuality      = 90;
                IntermecCamera.SnapshotFile.Directory       = "\\Temp";
                IntermecCamera.SnapshotFile.Filename        = _sFileTemplate;
                IntermecCamera.SnapshotFile.FilenamePadding = Camera.FilenamePaddingType.IncrementalCounter; // None;// Camera.FilenamePaddingType.IncrementalCounter;

                showSnapshot(true);                                                                          //show a still image

#if STREAMING_ON
                addLog("Init(): we DO NOT SWITCH streaming");
#else
                addLog("Init() IntermecCamera.Streaming=false...");
                IntermecCamera.Streaming = false;   //we use streaming=true ALL THE TIME
#endif

                ITCTools.KeyBoard.mapKey(); //map the scan button to Event Index 5

                //start the scan button watch thread
                addLog("IntermecBarcodescanControl: starting named event watch thread...");
                waitThread = new System.Threading.Thread(waitLoop);
                waitThread.Start();
                //######### TEST ####### does not fix problem with NO STREAM AT FIRST INIT()!
                //addLog("Init() IntermecCamera.Streaming=true at END of INIT()...");
                //IntermecCamera.Streaming = true;   //we use streaming=true ALL THE TIME

                //CameraPreview.Refresh();
                //ImageIsInPreview();

                // Hook the snapshot event.
                IntermecCamera.SnapshotEvent += new SnapshotEventHandler(IntermecCamera_SnapshotEvent);
            }
            catch (Intermec.Multimedia.CameraException ex)
            {
                addLog("CameraException in CameraInit. Is the runtime 'CNxDShow.CAB' installed? " + ex.Message);
            }
            catch (Exception ex)
            {
                addLog("Exception in CameraInit. Is the runtime 'CNxDShow.CAB' installed?\n" + ex.Message);
            }
            if (IntermecCamera == null)
            {
                System.Diagnostics.Debug.WriteLine("Exception in CameraInit. Is the runtime 'CNxDShow.CAB' installed?");
                throw new FileNotFoundException("Missing Runtimes. Is CNxDShow.CAB installed?");
            }

            //if (IntermecCamera == null)
            //    return;
        }
コード例 #36
0
 // public static string LOG = "";
 public GatewayServer()
 {
     _Running = true;
     _Thread  = new System.Threading.Thread(new System.Threading.ThreadStart(_Run));
     _Thread.Start();
 }
コード例 #37
0
        public void doDirtyTwoTurnsim()
        {
            //return;
            if (this.dirtyTwoTurnSim == 0)
            {
                return;
            }
            this.posmoves.Clear();
            int thread = 0;

            //DateTime started = DateTime.Now;

            //set maxwide of enemyturnsimulator's to second step (this value is higher than the maxwide in first step)
            foreach (EnemyTurnSimulator ets in Ai.Instance.enemyTurnSim)
            {
                ets.setMaxwideSecondStep(true);
            }

            if (Settings.Instance.numberOfThreads == 1)
            {
                foreach (Playfield p in this.twoturnfields)
                {
                    if (p.ownHero.Hp >= 1 && p.enemyHero.Hp >= 1)
                    {
                        p.value = int.MinValue;
                        //simulateEnemysTurn(simulateTwoTurns, playaround, print, pprob, pprob2);
                        p.prepareNextTurn(p.isOwnTurn);
                        p.turnCounter = 1;//correcting turncoutner: because we performed turncounter++ in the firstloop, but we perform first enemy turn also in this loop
                        Ai.Instance.enemyTurnSim[thread].simulateEnemysTurn(p, true, playaround, false, this.playaroundprob, this.playaroundprob2);
                    }
                    else
                    {
                        //p.value = -10000;
                    }
                    //Ai.Instance.enemyTurnSim.simulateEnemysTurn(p, true, this.playaround, false, this.playaroundprob, this.playaroundprob2);
                    this.posmoves.Add(p);
                }
            }
            else
            {
                //multithreading!

                List <System.Threading.Thread> tasks = new List <System.Threading.Thread>(Settings.Instance.numberOfThreads);
                for (int kl = 0; kl < Settings.Instance.numberOfThreads; kl++)
                {
                    if (this.threadresults.Count > kl)
                    {
                        this.threadresults[kl].Clear();
                        continue;
                    }
                    this.threadresults.Add(new List <Playfield>());
                }


                int k = 0;
                for (k = 0; k < Settings.Instance.numberOfThreads; k++)
                {
                    //System.Threading.Thread threadl = new System.Threading.Thread(() => this.Workthread(test, botBase, isLethalCheck, playfieldsTasklist[k], threadnumbers[k]));
                    System.Threading.Thread threadl = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.dirtyWorkthread));
                    //System.Threading.Tasks.Task tsk = new System.Threading.Tasks.Task(this.Workthread, (object)new threadobject(test, botBase, isLethalCheck, playfieldsTasklist[k], threadnumbers[k]));
                    int i = k;
                    threadl.Start((object)i);

                    tasks.Add(threadl);
                }

                System.Threading.Thread.Sleep(1);

                for (int j = 0; j < Settings.Instance.numberOfThreads; j++)
                {
                    tasks[j].Join();
                    posmoves.AddRange(this.threadresults[j]);
                }
            }

            //just for debugging
            posmoves.Sort((a, b) => - (botBase.getPlayfieldValue(a)).CompareTo(botBase.getPlayfieldValue(b)));//want to keep the best

            //Helpfunctions.Instance.ErrorLog("time needed for parallel: " + (DateTime.Now - started).TotalSeconds);
        }
コード例 #38
0
ファイル: frmReport.cs プロジェクト: toantranit/QuanLyTaiSan
        private void simpleButton_Xuat_Click(object sender, EventArgs e)
        {
            switch (comboBoxEdit_LoaiBaoCao.SelectedIndex)
            {
                #region Báo cáo tăng giảm tài sản cố định

            case 0:
                if (dateEdit_TuNgay.DateTime.Date > DateTime.Today.Date)
                {
                    XtraMessageBox.Show("Ngày từ không được lớn hơn ngày hiện tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dateEdit_TuNgay.Focus();
                    return;
                }
                if (dateEdit_DenNgay.DateTime.Date > DateTime.Today.Date)
                {
                    XtraMessageBox.Show("Ngày đến không được lớn hơn ngày hiện tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dateEdit_DenNgay.Focus();
                    return;
                }
                if (dateEdit_TuNgay.DateTime.Date > dateEdit_DenNgay.DateTime.Date)
                {
                    XtraMessageBox.Show("Ngày từ không được lớn hơn ngày đến", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dateEdit_TuNgay.Focus();
                    return;
                }
                if (checkEdit_XuatBaoCao.Checked)
                {
                    IsDesign = false;
                }
                else if (checkEdit_ThietKe.Checked)
                {
                    IsDesign = true;
                }

                ShowAndHide(false);
                labelControl_Status.Text = "Đang tạo report, vui lòng chờ trong giây lát...";

                _ThreadReport = new System.Threading.Thread(() =>
                {
                    DevExpress.UserSkins.BonusSkins.Register();
                    Application.EnableVisualStyles();
                    UserLookAndFeel.Default.SetSkinStyle(TSCD.Global.local_setting.ApplicationSkinName);
                    DevExpress.Skins.SkinManager.EnableFormSkins();

                    DateTime From = dateEdit_TuNgay.DateTime.Date, To = dateEdit_DenNgay.DateTime.Date;
                    List <TK_TangGiam_TheoLoaiTS> Data = GetData_BaoCaoTangGiamTaiSanCoDinh(From, To);

                    TSCD_GUI.ReportTSCD.XtraReport_BaoCaoTangGiamTSCD _XtraReport_BaoCaoTangGiamTSCD = new ReportTSCD.XtraReport_BaoCaoTangGiamTSCD(Data, From, To);
                    if (IsDesign)
                    {
                        ReportDesignTool designTool = new ReportDesignTool(_XtraReport_BaoCaoTangGiamTSCD);

                        ReportCompeleted();

                        designTool.ShowDesignerDialog();

                        ReportPrintTool printTool = new ReportPrintTool(designTool.Report);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                    else
                    {
                        ReportPrintTool printTool = new ReportPrintTool(_XtraReport_BaoCaoTangGiamTSCD);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        ReportCompeleted();

                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                });
                _ThreadReport.SetApartmentState(ApartmentState.STA);
                _ThreadReport.Start();
                break;

                #endregion

                #region Sổ tài sản cố định

            case 1:
                if (dateEdit_Nam.DateTime.Year > DateTime.Today.Year)
                {
                    XtraMessageBox.Show("Năm lớn hơn năm hiện tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List <Guid> ListLoaiTaiSan = ucComboBoxLoaiTS_LoaiTaiSan.list_loaitaisan;
                if (Object.Equals(ListLoaiTaiSan, null))
                {
                    XtraMessageBox.Show("Chưa chọn loại tài sản cần thống kê", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (!(ListLoaiTaiSan.Count > 0))
                {
                    XtraMessageBox.Show("Chưa chọn loại tài sản cần thống kê", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List <Guid> ListCoSo = CheckedComboBoxEditHelper.getCheckedValueArray(checkedComboBoxEdit_ChonCoSo);
                if (!checkEdit_ChuaCoViTri.Checked)
                {
                    if (Object.Equals(ListCoSo, null))
                    {
                        XtraMessageBox.Show("Chưa chọn cơ sở cần thống kê", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    if (!(ListCoSo.Count > 0))
                    {
                        XtraMessageBox.Show("Chưa chọn cơ sở cần thống kê", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                if (checkEdit_XuatBaoCao.Checked)
                {
                    IsDesign = false;
                }
                else if (checkEdit_ThietKe.Checked)
                {
                    IsDesign = true;
                }

                ShowAndHide(false);
                labelControl_Status.Text = "Đang tạo report, vui lòng chờ trong giây lát...";

                _ThreadReport = new System.Threading.Thread(() =>
                {
                    DevExpress.UserSkins.BonusSkins.Register();
                    Application.EnableVisualStyles();
                    UserLookAndFeel.Default.SetSkinStyle(TSCD.Global.local_setting.ApplicationSkinName);
                    DevExpress.Skins.SkinManager.EnableFormSkins();

                    Object Data = GetData_SoTaiSanCoDinh(ListLoaiTaiSan, ListCoSo, dateEdit_Nam.DateTime.Year, checkEdit_ChuaCoViTri.Checked);

                    TSCD_GUI.ReportTSCD.XtraReport_SoTaiSanCoDinh _XtraReport_SoTaiSanCoDinh = new ReportTSCD.XtraReport_SoTaiSanCoDinh(Data, dateEdit_Nam.DateTime.Year);
                    if (IsDesign)
                    {
                        ReportDesignTool designTool = new ReportDesignTool(_XtraReport_SoTaiSanCoDinh);

                        ReportCompeleted();

                        designTool.ShowDesignerDialog();

                        ReportPrintTool printTool = new ReportPrintTool(designTool.Report);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                    else
                    {
                        ReportPrintTool printTool = new ReportPrintTool(_XtraReport_SoTaiSanCoDinh);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        ReportCompeleted();

                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                });
                _ThreadReport.SetApartmentState(ApartmentState.STA);
                _ThreadReport.Start();
                break;

                #endregion

                #region Sổ chi tiết tài sản cố định

            case 2:
                if (dateEdit_Nam.DateTime.Year > DateTime.Today.Year)
                {
                    XtraMessageBox.Show("Năm lớn hơn năm hiện tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (Object.Equals(ucComboBoxDonVi_ChonDonVi.DonVi, null))
                {
                    XtraMessageBox.Show("Chưa chọn đơn vị", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (Object.Equals(ucComboBoxDonVi_ChonDonVi.DonVi.id, Guid.Empty))
                {
                    XtraMessageBox.Show("Chưa chọn đơn vị", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (checkEdit_XuatBaoCao.Checked)
                {
                    IsDesign = false;
                }
                else if (checkEdit_ThietKe.Checked)
                {
                    IsDesign = true;
                }

                ShowAndHide(false);
                labelControl_Status.Text = "Đang tạo report, vui lòng chờ trong giây lát...";

                _ThreadReport = new System.Threading.Thread(() =>
                {
                    DevExpress.UserSkins.BonusSkins.Register();
                    Application.EnableVisualStyles();
                    UserLookAndFeel.Default.SetSkinStyle(TSCD.Global.local_setting.ApplicationSkinName);
                    DevExpress.Skins.SkinManager.EnableFormSkins();

                    var DonViSelected  = ucComboBoxDonVi_ChonDonVi.DonVi;
                    Object Data        = null;
                    String strTenDonVi = "";
                    if (!Object.Equals(DonViSelected, null))
                    {
                        strTenDonVi = DonViSelected.ten;
                        Data        = GetData_SoChiTietTaiSanCoDinh(DonViSelected.id, dateEdit_Nam.DateTime.Year);
                    }

                    TSCD_GUI.ReportTSCD.XtraReport_SoChiTietTaiSanCoDinh _XtraReport_SoChiTietTaiSanCoDinh = new ReportTSCD.XtraReport_SoChiTietTaiSanCoDinh(Data, dateEdit_Nam.DateTime.Year, strTenDonVi);
                    if (IsDesign)
                    {
                        ReportDesignTool designTool = new ReportDesignTool(_XtraReport_SoChiTietTaiSanCoDinh);

                        ReportCompeleted();

                        designTool.ShowDesignerDialog();

                        ReportPrintTool printTool = new ReportPrintTool(designTool.Report);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                    else
                    {
                        ReportPrintTool printTool = new ReportPrintTool(_XtraReport_SoChiTietTaiSanCoDinh);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        ReportCompeleted();

                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                });
                _ThreadReport.SetApartmentState(ApartmentState.STA);
                _ThreadReport.Start();
                break;

                #endregion

                #region Sổ theo dõi tài sản cố định tại nơi sử dụng

            case 3:
                if (Object.Equals(ucComboBoxDonVi_ChonDonVi.DonVi, null))
                {
                    XtraMessageBox.Show("Chưa chọn đơn vị", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (Object.Equals(ucComboBoxDonVi_ChonDonVi.DonVi.id, Guid.Empty))
                {
                    XtraMessageBox.Show("Chưa chọn đơn vị", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (checkEdit_XuatBaoCao.Checked)
                {
                    IsDesign = false;
                }
                else if (checkEdit_ThietKe.Checked)
                {
                    IsDesign = true;
                }

                ShowAndHide(false);
                labelControl_Status.Text = "Đang tạo report, vui lòng chờ trong giây lát...";

                _ThreadReport = new System.Threading.Thread(() =>
                {
                    DevExpress.UserSkins.BonusSkins.Register();
                    Application.EnableVisualStyles();
                    UserLookAndFeel.Default.SetSkinStyle(TSCD.Global.local_setting.ApplicationSkinName);
                    DevExpress.Skins.SkinManager.EnableFormSkins();

                    var DonViSelected  = ucComboBoxDonVi_ChonDonVi.DonVi;
                    Object Data        = null;
                    String strTenDonVi = "";
                    if (!Object.Equals(DonViSelected, null))
                    {
                        strTenDonVi = DonViSelected.ten;
                        Data        = GetData_SoTheoDoiTaiSanCoDinhTaiNoiSuDung(DonViSelected.id);
                    }

                    TSCD_GUI.ReportTSCD.XtraReport_SoTheoDoiTSCDTaiNoiSuDung _XtraReport_SoTheoDoiTSCDTaiNoiSuDung = new ReportTSCD.XtraReport_SoTheoDoiTSCDTaiNoiSuDung(Data, strTenDonVi);
                    if (IsDesign)
                    {
                        ReportDesignTool designTool = new ReportDesignTool(_XtraReport_SoTheoDoiTSCDTaiNoiSuDung);

                        ReportCompeleted();

                        designTool.ShowDesignerDialog();

                        ReportPrintTool printTool = new ReportPrintTool(designTool.Report);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                    else
                    {
                        ReportPrintTool printTool = new ReportPrintTool(_XtraReport_SoTheoDoiTSCDTaiNoiSuDung);
                        printTool.PreviewForm.PrintControl.Zoom = Zoom;
                        ReportCompeleted();

                        printTool.ShowPreviewDialog();

                        ShowAndHide(true);
                    }
                });
                _ThreadReport.SetApartmentState(ApartmentState.STA);
                _ThreadReport.Start();
                break;

                #endregion

            case 4:
                XtraMessageBox.Show("Chức năng này chưa có", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;

            default:
                break;
            }
        }
コード例 #39
0
ファイル: Thread.cs プロジェクト: shekky/NBoilerpipe
 public void Start()
 {
     thread.Start();
 }
コード例 #40
0
        public bool OnActionItemClicked(ActionMode mode, IMenuItem item)
        {
            switch (item.ItemId)
            {
            case Resource.Id.start:
                brickController.SpawnThread(delegate() {
                    FileItem currentItemSelected = adapter.SelectedItems.First();
                    if (currentItemSelected.FileType == MonoBrick.FileType.Program)
                    {
                        brickController.NXT.StartProgram(currentItemSelected.Name, true);
                        this.Activity.RunOnUiThread(delegate(){
                            TabActivity.ShowToast(this.Activity, "Program successfully started");
                        });
                    }
                    else
                    {
                        brickController.NXT.PlaySoundFile(currentItemSelected.Name, false, true);
                        this.Activity.RunOnUiThread(delegate(){
                            TabActivity.ShowToast(this.Activity, "Sound file started");
                        });
                    }
                });
                break;

            case Resource.Id.stop:
                brickController.SpawnThread(delegate() {
                    brickController.NXT.StopProgram(true);
                    this.Activity.RunOnUiThread(delegate(){
                        TabActivity.ShowToast(this.Activity, "All programs stoped");
                    });
                });
                break;

            case Resource.Id.delete:

                AlertDialog.Builder dialog = new AlertDialog.Builder(this.View.Context);
                dialog.SetIcon(Android.Resource.Drawable.IcMenuInfoDetails);
                dialog.SetTitle("Delete file(s)");
                string message;
                if (adapter.SelectedItems.Count > 1)
                {
                    message = "Are you sure you want to delete " + adapter.SelectedItems.Count + " files ?";
                }
                else
                {
                    message = "Are you sure you want to delete " + adapter.SelectedItems.First().Name + " ?";
                }
                dialog.SetMessage(message);
                dialog.SetPositiveButton("Yes", delegate(object sender, DialogClickEventArgs e){
                    ProgressDialog progress = null;
                    this.Activity.RunOnUiThread(delegate() {
                        progress = ProgressDialog.Show(this.View.Context, "Deleting files", "PLease Wait...       ");
                    });
                    System.Threading.Thread t = new System.Threading.Thread(delegate(object obj){
                        brickController.ExecuteOnCurrentThread(delegate() {
                            Exception ex = null;
                            List <FileItem> uncheckList = new List <FileItem>();
                            try{
                                int i = 0;
                                foreach (FileItem myFileItem in adapter.SelectedItems)
                                {
                                    if (adapter.SelectedItems.Count > 1)
                                    {
                                        progress.SetMessage("Deleteing file " + (i + 1) + " of " + adapter.SelectedItems.Count);
                                    }
                                    else
                                    {
                                        progress.SetMessage("Deleteing " + myFileItem.Name);
                                    }
                                    brickController.NXT.FileSystem.DeleteFile(myFileItem.Name);
                                    adapter.Items.Remove(myFileItem);
                                    uncheckList.Add(myFileItem);
                                    i++;
                                }
                            }
                            catch (Exception excep) {
                                ex = excep;
                            }
                            finally
                            {
                                foreach (FileItem fi in uncheckList)
                                {
                                    adapter.SelectedItems.Remove(fi);
                                }
                                this.Activity.RunOnUiThread(delegate() {
                                    progress.Dismiss();
                                    adapter.NotifyDataSetChanged();
                                    if (mode != null)
                                    {
                                        mode.Finish();
                                    }
                                });
                            }
                            if (ex != null)
                            {
                                throw ex;
                            }
                        });
                    });
                    t.IsBackground = true;
                    t.Priority     = System.Threading.ThreadPriority.Normal;
                    t.Start();
                });
                dialog.SetNegativeButton("No", delegate(object sender, DialogClickEventArgs e){});
                dialog.Show();
                break;

            case Resource.Id.download:
                Console.WriteLine("Download");
                break;
            }

            return(true);
        }
コード例 #41
0
ファイル: OpenDMXUSB2.cs プロジェクト: qcyb/TotalDMXControl
        private void InitializeDMXDevice()
        {
            connected = false;
            // not connected

            frameIntervalMs = 25;
            // default 30 ms between each frame
            startCode = 0;
            // default startcode of 0
            lastError = "";
            // no error has happened yet

            // ==== ATTEMPT TO OPEN DEVICE ====
            if (FT_Open(deviceIndex, ref deviceHandle) != FT_OK)
            {
                lastError = "Not Found";
                throw new Exception(lastError);
                return;
            }
            // ==== PREPARE DEVICE FOR DMX TRANSMISSION ====
            // reset the device
            if (FT_ResetDevice(deviceHandle) != FT_OK)
            {
                lastError = "Failed To Reset Device!";
                throw new Exception(lastError);
                return;
            }

            // get an ID from the widget from jumpers
            GetID();

            // set the baud rate
            if (FT_SetDivisor(deviceHandle, 12) != FT_OK)
            {
                lastError = "Failed To Set Baud Rate!";
                throw new Exception(lastError);
                return;
            }
            // shape the line
            if (FT_SetDataCharacteristics(deviceHandle, Convert.ToByte(FT_BITS_8), Convert.ToByte(FT_STOP_BITS_2), Convert.ToByte(FT_PARITY_NONE)) != FT_OK)
            {
                lastError = "Failed To Set Data Characteristics!";
                throw new Exception(lastError);
                return;
            }
            // no flow control
            if (FT_SetFlowControl(deviceHandle, FT_FLOW_NONE, 0, 0) != FT_OK)
            {
                lastError = "Failed to set flow control!";
                throw new Exception(lastError);
                return;
            }
            // set bus transiever to transmit enable
            if (FT_ClrRts(deviceHandle) != FT_OK)
            {
                lastError = "Failed to set RS485 to send!";
                throw new Exception(lastError);
                return;
            }
            // Clear TX & RX buffers
            if (FT_Purge(deviceHandle, FT_PURGE_TX) != FT_OK)
            {
                lastError = "Failed to purge TX buffer!";
                throw new Exception(lastError);
                return;
            }
            // empty buffers
            if (FT_Purge(deviceHandle, FT_PURGE_RX) != FT_OK)
            {
                lastError = "Failed to purge RX buffer!";
                throw new Exception(lastError);
                return;
            }
            writeBuffer = "";
            // clear the software buffer
            bytesWritten = 0;
            // clear byte counter

            // Success
            connected = true;
            // device connected

            // start/resume threads

            lastError = "Starting Thread";
            dmxThread = new Thread(DmxThread);
            dmxThread.IsBackground = true;
            dmxThread.Start();
            // start the thread
            // highest priority
            dmxThread.Priority = ThreadPriority.AboveNormal;
        }
コード例 #42
0
ファイル: Form12.cs プロジェクト: chenliang123/liaoNingYiDong
        /// <summary>
        /// 刷新控件
        /// </summary>
        private void RefreshControls()
        {
            submitStr = "";
            this.panel2.Controls.Clear();
            this.panel3.Controls.Clear();
            int i = 0;
            int x = 8, y = 29;

            if (btnList == null)
            {
                btnList = new ArrayList();
            }
            for (int k = 0; k < btnList.Count; k++)//
            {
                Button btn = (Button)btnList[k];
                btn.FlatAppearance.BorderSize = 0;
                btn.BackColor = System.Drawing.Color.FromArgb(255, 255, 255);
                btn.Location  = new System.Drawing.Point(x, y);
                x            += btn.Width + 8;
                if ((i + 1) % 6 == 0)
                {
                    x  = 8;
                    y += btn.Height + 29;
                }
                i++;
                this.panel3.Controls.Add(btn);
            }
            int j = 0;
            int x1 = 32, y1 = 20;

            for (int k = 0; k < btnRightList.Count; k++)
            {
                Button btn = (Button)btnRightList[k];
                btn.FlatAppearance.BorderSize = 0;
                btn.BackColor = System.Drawing.Color.FromArgb(255, 255, 255);
                btn.Location  = new System.Drawing.Point(x1, y1);
                x1           += btn.Width + 32;
                if ((j + 1) % 3 == 0)
                {
                    x1  = 32;
                    y1 += btn.Height + 20;
                }
                j++;
                this.panel2.Controls.Add(btn);
                if (k == 0)
                {
                    submitStr += btn.Name.Split('|')[2].ToString();
                }
                else
                {
                    submitStr += "|" + btn.Name.Split('|')[2].ToString();
                }
            }

            //同步到云端
            g_filenames = submitStr;

            //同步到云端
            System.Threading.Thread thred = new System.Threading.Thread(AsnycSubmit);
            thred.Start();
        }
コード例 #43
0
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            if (listener != null)
            {
                listener.Stop();
                listener = null;
            }

            if (threadrun)
            {
                threadrun = false;
                if (CoTStream != null && CoTStream.IsOpen)
                {
                    CoTStream.Close();
                }
                BUT_connect.Text = Strings.Connect;
                return;
            }

            try
            {
                switch (CMB_serialport.Text)
                {
                case "TCP Host - 14551":
                case "TCP Host":
                    CoTStream = new TcpSerial();
                    CMB_baudrate.SelectedIndex = 0;
                    listener = new TcpListener(System.Net.IPAddress.Any, 14551);
                    listener.Start(0);
                    listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
                    BUT_connect.Text = Strings.Stop;
                    break;

                case "TCP Client":
                    CoTStream = new TcpSerial()
                    {
                        retrys = 999999, autoReconnect = true
                    };
                    CMB_baudrate.SelectedIndex = 0;
                    break;

                case "UDP Host - 14551":
                    CoTStream = new UdpSerial();
                    CMB_baudrate.SelectedIndex = 0;
                    break;

                case "UDP Client":
                    CoTStream = new UdpSerialConnect();
                    CMB_baudrate.SelectedIndex = 0;
                    break;

                default:
                    CoTStream          = new SerialPort();
                    CoTStream.PortName = CMB_serialport.Text;
                    break;
                }
            }
            catch
            {
                CustomMessageBox.Show(Strings.InvalidPortName);
                return;
            }
            try
            {
                CoTStream.BaudRate = int.Parse(CMB_baudrate.Text);
            }
            catch
            {
                CustomMessageBox.Show(Strings.InvalidBaudRate);
                return;
            }
            try
            {
                if (listener == null)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(background_DoOpen);
                }
            }
            catch
            {
                CustomMessageBox.Show("Error Connecting\nif using com0com please rename the ports to COM??");
                return;
            }

            t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
            {
                IsBackground = true,
                Name         = "CoT output"
            };
            t12.Start();

            BUT_connect.Text = Strings.Stop;
        }
コード例 #44
0
 /**
  * Connect to the remote ros environment.
  */
 public void Connect()
 {
     _myThread = new System.Threading.Thread(Run);
     _myThread.Start();
 }
コード例 #45
0
 /// <summary>
 /// 开始监听
 /// </summary>
 public void StartListening()
 {
     lister.Start();
 }
コード例 #46
0
        //连接设备、断开设备
        private void ConnectDevice(DeviceType DevType)
        {
            bool IsConnected  = false;
            byte MyDeviceType = Convert.ToByte(DevType);//设备类型转换为byte

            if (DriverConnected[MyDeviceType] == false)
            {
                if (!string.IsNullOrEmpty(DriverID[MyDeviceType]))//DriverID不为空
                {
                    switch (MyDeviceType)
                    {
                    case 0:
                        MyCamera           = new SSCamera(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyCamera.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyCamera.Connected)
                            {
                                IsConnected = true;
                                TCamera     = new Thread(this.CameraThread); TCamera.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 1:
                        MyDome           = new SSDome(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyDome.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyDome.Connected)
                            {
                                IsConnected = true;
                                TDome       = new Thread(this.DomeThread); TDome.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 2:
                        MyFilterWheel           = new SSFilterWheel(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyFilterWheel.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyFilterWheel.Connected)
                            {
                                IsConnected = true;
                                //TFilterWheel = new Thread(this.FilterWheelThread);//TFilterWheel.Start();//由Camera线程调度,不用单开线程
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 3:
                        MyFocuser           = new SSFocuser(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyFocuser.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyFocuser.Connected)
                            {
                                IsConnected = true;
                                TFocuser    = new Thread(this.FocuserThread); TFocuser.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 4:
                        MyObsConditions           = new SSObservingConditions(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyObsConditions.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyObsConditions.Connected)
                            {
                                IsConnected    = true;
                                TObsConditions = new Thread(this.ObsConditionsThread); TObsConditions.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 5:
                        MyRotator           = new SSRotator(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyRotator.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyRotator.Connected)
                            {
                                IsConnected = true;
                                TRotator    = new Thread(this.RotatorThread); TRotator.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 6:
                        MySwitch           = new SSSwitch(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MySwitch.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MySwitch.Connected)
                            {
                                IsConnected = true;
                                TSwitch     = new Thread(this.SwitchThread); TSwitch.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;

                    case 7:
                        MyTelescope           = new SSTelescope(DriverID[MyDeviceType], DriverType[MyDeviceType]);
                        MyTelescope.Connected = true;
                        for (byte i = 0; i < ConnectTimeout * 2; i++)
                        {
                            if (MyTelescope.Connected)
                            {
                                IsConnected = true;
                                TTelescope  = new Thread(this.TelescopeThread); TTelescope.Start();
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        break;
                    }
                    if (IsConnected)
                    {
                        DriverConnected[MyDeviceType]      = true;
                        ButtonConnected[MyDeviceType].Text = "Disconnect";
                    }
                    else
                    {
                        DriverConnected[MyDeviceType]      = false;
                        ButtonConnected[MyDeviceType].Text = "Connect";
                        MessageBox.Show("Connect failed");
                    }
                }
            }
            else
            {
                switch (MyDeviceType)
                {
                case 0:
                    MyCamera.Connected = false;    //TCamera.Abort();//MyCamera.Dispose();
                    break;

                case 1:
                    MyDome.Connected = false;    //TDome.Abort();//MyDome.Dispose();
                    break;

                case 2:
                    MyFilterWheel.Connected = false;    //TFilterWheel.Abort();//MyFilterWheel.Dispose();
                    break;

                case 3:
                    MyFocuser.Connected = false;    //TFocuser.Abort();//MyFocuser.Dispose();
                    break;

                case 4:
                    MyObsConditions.Connected = false;    //TObsConditions.Abort();//MyObsConditions.Dispose();
                    break;

                case 5:
                    MyRotator.Connected = false;    //TRotator.Abort();//MyRotator.Dispose();
                    break;

                case 6:
                    MySwitch.Connected = false;    //TSwitch.Abort();//MySwitch.Dispose();
                    break;

                case 7:
                    MyTelescope.Connected = false;    //TTelescope.Abort();//MyTelescope.Dispose();
                    break;
                }
                DriverConnected[MyDeviceType]      = false;
                ButtonConnected[MyDeviceType].Text = "Connect";
            }
        }
コード例 #47
0
 public SimBike(BikeData data)
 {
     this.Data = data;
     System.Threading.Thread thread = new System.Threading.Thread(new ThreadStart(WorkThreadFunction));
     thread.Start();
 }