这是我的项目要求:
到目前为止,我有:
我的问题是:
我的一些代码如下所示:
[ServiceContract(Namespace = "...")]
public interface IMyService
{
[OperationContract]
void StartProcess(int MIndexId, int MProcessId);
[OperationContract]
void StopProcess(int MIndexProcessId);
}
public class MyService : IMyService
{
private static MyThreadPool threadPool = new MyThreadPool();
public void StopProcess(int MIndexProcessId)
{
throw new NotImplementedException();
}
public void StartProcess(int ItemIdToProcess, int ProcessTypeId)
{
// call threadPool.LaunchThread(...)
}
}
public class MyThreadPool
{
private ConcurrentDictionary<int, BaseThread> _threads;
...
public void LaunchThread(BaseThread thread, int ItemIdToProcess)
{
// set additional data for thread (such as a key and name) for tracking in a database
_threads.AddOrUpdate(ItemIdToProcess, thread, (key, oldValue) => { return oldValue; });
thread.Start();
}
public void KillThread(int ItemIdToProcess)
{
...
}
}
public abstract class BaseThread
{
// some additional properties for tracking thread
// ...
private Thread _thread;
protected BaseThread()
{
_thread = new Thread(new ThreadStart(this.RunThread));
_thread.IsBackground = true;
}
// Thread methods / properties
public void Start() { _thread.Start(); }
public void Join() { _thread.Join(); }
public bool IsAlive { get { return _thread.IsAlive; } }
public string Name
{
get
{
return _thread.Name;
}
set
{
_thread.Name = value;
}
}
public void Abort()
{
_thread.Abort();
}
public abstract void RunThread();
}
public class ValidateThread : BaseThread
{
public override void RunThread()
{
...
// indicate to calling thread to remove from thread list();
}
}
最佳答案
Task
与LongRunning
选项一起使用。编写任务很容易。 Windows服务像其他任何其他应用程序一样,大多是由外部启动的exe。
但是,一件不好的事情是:
_thread.Abort();
Thread.Abort is evil。 .NET中的取消必须(不应该)合作。
关于c# - 线程完成后如何从ConcurrentDictionary <int,Thread>中删除线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22788578/