[英]C# Call a method in a new thread
我正在寻找一种在新线程上调用方法的方法(使用 C#)。
例如,我想在一个新线程上调用SecondFoo()
。 但是,我希望在SecondFoo()
完成时终止线程。
我在C#
看到了几个线程的例子,但没有一个适用于我需要生成的线程终止自身的特定场景。 这可能吗?
如何强制运行Secondfoo()
的生成线程在完成时终止?
有没有人遇到过这样的例子?
如果您实际启动了一个新线程,则该线程将在该方法完成时终止:
Thread thread = new Thread(SecondFoo);
thread.Start();
现在SecondFoo
将在新线程中被调用,线程将在完成时终止。
你真的是说你希望线程在调用线程中的方法完成时终止吗?
编辑:请注意,启动线程是一个相当昂贵的操作。 你肯定需要一个全新的线程而不是使用线程池线程吗? 考虑使用ThreadPool.QueueUserWorkItem
或(最好,如果您使用 .NET 4) TaskFactory.StartNew
。
它真的必须是一个线程,还是也可以是一个任务?
如果是这样,最简单的方法是:
Task.Factory.StartNew(() => SecondFoo())
一旦线程启动,就没有必要保留对 Thread 对象的引用。 线程继续执行直到线程过程结束。
new Thread(new ThreadStart(SecondFoo)).Start();
异步版本:
private async Task DoAsync()
{
await Task.Run(async () =>
{
//Do something awaitable here
});
}
除非您有特殊情况需要非线程池线程,否则只需使用这样的线程池线程:
Action secondFooAsync = new Action(SecondFoo);
secondFooAsync.BeginInvoke(new AsyncCallback(result =>
{
(result.AsyncState as Action).EndInvoke(result);
}), secondFooAsync);
保证调用 EndInvoke 来为您处理清理工作。
据我了解,您需要将终止作为Thread.Abort()
对吗? 在这种情况下,您可以退出 Foo()。 或者您可以使用Process来捕获线程。
Thread myThread = new Thread(DoWork);
myThread.Abort();
myThread.Start();
流程示例:
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;
class PrintProcessClass
{
private Process myProcess = new Process();
private int elapsedTime;
private bool eventHandled;
// Print a file with any known extension.
public void PrintDoc(string fileName)
{
elapsedTime = 0;
eventHandled = false;
try
{
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = fileName;
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
return;
}
// Wait for Exited event, but not more than 30 seconds.
const int SLEEP_AMOUNT = 100;
while (!eventHandled)
{
elapsedTime += SLEEP_AMOUNT;
if (elapsedTime > 30000)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
}
}
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
eventHandled = true;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
}
public static void Main(string[] args)
{
// Verify that an argument has been entered.
if (args.Length <= 0)
{
Console.WriteLine("Enter a file name.");
return;
}
// Create the process and print the document.
PrintProcessClass myPrintProcess = new PrintProcessClass();
myPrintProcess.PrintDoc(args[0]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.