我正在运行一个自托管的 WCF 服务(它将是一个 Windows 服务,但我将它作为控制台应用程序运行以进行调试)。服务器端代码在调用时需要做一些工作。然后将结果同步回传给客户端。然后它需要继续并做一些更密集的长时间运行的处理。(即异步)
代码的简化说明是:
[ServiceBehavior(IncludeExceptionDetailInFaults = true,InstanceContextMode = InstanceContextMode.PerCall)]
public class MyWCFService : IMyWCFService, IDisposable {
private Thread importThread;
private DoWork importWork;
public MyImportResultContract StartImport(MyImportRequestContract requestParams) {
processorResult = new MyImportResultContract();
//Simulate a short piece of work here to return results to the
//caller before calling a Thread to do more processing
processorResult.Success = true;
processorResult.Messages = "A message to pass back to caller"
Console.WriteLine("WCF Class ManagedThreadId = " + Thread.CurrentThread.ManagedThreadId);
//Thread off to do long running process
importWork = new DoWork();
importThread = new Thread(importWork.Start);
importThread.Start();
//Pass back the results
return processorResult;
}
public void Dispose() {
Console.WriteLine("WCF Class Dispose : " + DateTime.Now.ToLongTimeString());
}
}
internal class DoWork : IDisposable {
public void Start() {
Console.WriteLine("Thread ManagedThreadId = " + Thread.CurrentThread.ManagedThreadId);
//Simulate a long running process
Thread.Sleep(60000);
Console.WriteLine("Thread Finished");
}
public void Dispose() {
Console.WriteLine("DoWork Class Dispose : " + DateTime.Now.ToLongTimeString());
}
}
我有 2 个问题:
1. 我看到在它产生的线程继续并完成之前调用了服务类的 Dispose。我担心的是,Service 类实例可能不会因为它产生的线程而被释放用于垃圾收集。此处概述的代码是否可靠,不会发生这种情况?
2. 该服务自托管在 Windows 服务中。如果对任何衍生线程停止服务会发生什么?有没有办法让服务等到任何仍在运行的线程完成?