gpt4 book ai didi

c# - 如何在线程工作时停止服务(不使用 Thread.Abort)

转载 作者:行者123 更新时间:2023-11-30 14:15:48 30 4
gpt4 key购买 nike

我有一个服务在循环中运行一些不同的任务,直到服务停止。但是,其中一项任务我调用了 Web 服务,并且此调用可能需要几分钟才能完成。我希望能够立即停止服务,在不调用 Thread.Abort 的情况下“取消”Web 服务调用,因为这会导致一些奇怪的行为,即使线程正在做的唯一事情就是调用此 Web 服务方法。

如何取消或中断同步方法调用(如果可能的话)?或者我应该尝试不同的方法吗?

我尝试使用 AutoResetEvent,然后调用 Thread.Abort,这在下面的代码示例中运行良好,但是在实际服务中实现此解决方案时我得到一些意外的行为可能是因为我正在使用的外部库中发生了什么。

AutoResetEventThread.Abort:

class Program
{
static void Main(string[] args)
{
MainProgram p = new MainProgram();
p.Start();
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Q)
p.Stop();
}
}

class MainProgram
{
private Thread workerThread;
private Thread webServiceCallerThread;
private volatile bool doWork;

public void Start()
{
workerThread = new Thread(() => DoWork());
doWork = true;
workerThread.Start();
}

public void Stop()
{
doWork = false;
webServiceCallerThread.Abort();
}

private void DoWork()
{
try
{
while (doWork)
{
AutoResetEvent are = new AutoResetEvent(false);
WebServiceCaller caller = new WebServiceCaller(are);
webServiceCallerThread = new Thread(() => caller.TimeConsumingMethod());
webServiceCallerThread.Start();

// Wait for the WebServiceCaller.TimeConsumingMethod to finish
WaitHandle.WaitAll(new[] { are });

// If doWork has been signalled to stop
if (!doWork)
break;

// All good - continue
Console.WriteLine(caller.Result);
}
}
catch (Exception e)
{
Console.Write(e);
}
}
}

class WebServiceCaller
{
private AutoResetEvent ev;
private int result;

public int Result
{
get { return result; }
}

public WebServiceCaller(AutoResetEvent ev)
{
this.ev = ev;
}

public void TimeConsumingMethod()
{
try
{
// Simulates a method running for 1 minute
Thread.Sleep(60000);
result = 1;
ev.Set();
}
catch (ThreadAbortException e)
{
ev.Set();
result = -1;
Console.WriteLine(e);
}
}
}

有人可以建议解决这个问题吗?

最佳答案

试试这个

public void Start()
{
workerThread = new Thread(() => DoWork());
doWork = true;
workerThread.IsBackground = true;
workerThread.Start();
}

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

有关详细信息,请参阅 http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx

关于c# - 如何在线程工作时停止服务(不使用 Thread.Abort),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9273480/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com