我正在运行一个自托管的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());
}
}
我有两个问题:
1.我看到在它生成的线程进行并完成之前调用的服务类的Dispose。我担心的是,由于它产生的线程,可能没有为Garbage集合释放Service类实例。此处列出的代码是否牢固,以便不会发生这种情况?
2.该服务是在Windows服务中自托管的。如果服务停止到任何生成的线程会发生什么?有没有办法让服务等到任何线程仍然运行完毕?
答案 0 :(得分:0)
Task
而不是Thread
,这将更容易实现。您可能需要保留正在处理的全局任务列表,以便关闭代码可以WaitAll
执行这些任务。