gpt4 book ai didi

c# - 使用线程正确处理类

转载 作者:太空狗 更新时间:2023-10-30 00:47:07 25 4
gpt4 key购买 nike

我有一个相当复杂的多线程 Windows 服务在工作,但我不知道如何正确清理。下面是一些[伪]代码来展示我所拥有的。实际代码要复杂得多,复制/粘贴到这里可能太多了。

基本上,我有一个创建线程来完成工作的请求类。当新请求进入监听器时,它会将其发送到处理器,处理器创建新请求并维护请求列表。如果服务停止,我会清除列表中的所有请求。但是当 Request 工作完成后,我该如何清理该类的一个实例?

感谢您的帮助!

尼尔森

class Service
{
Listener listener;
Processor processor;

OnStart()
{
processor = new Processor();
listener = new Listener(processor);
}

OnStop()
{
listener.Dispose();
processor.Dispose();
}
}

class Listener
{
Thread thread;
bool terminate = false;

Listener(Processor processor)
{
thread = new Thread(DoWork);
thread.Start(processor);
}

DoWork(Processor processor)
{
WaitForConnection(NewConnection);
}

NewConnection(String data)
{
processor.NewRequest(data);

if (terminate)
return;

WaitForConnection(NewConnection);
}

Dispose()
{
terminate = true;
thread.Join();
}
}

class Processor
{
//I need to maintain this list so that when the service stops I can cleanly close down
List<Request> requests = new List<Request>();

NewRequest(string data)
{
request.Add(new Request(data));
}

Dispose()
{
//Cleanup each request
foreach (Request request in requests)
{
request.Dispose();
}
}
}

class Request
{
Thread thread;
bool terminate;

Request(string data)
{
while (true)
{
//Do some work
Thread.Sleep(1000);

if (doneWorking)
break;

if (terminate)
return;
}

//We're done. If I return this thread stops. But how do I properly remove this Request instance from the Processor.requests list?
}

Dispose()
{
terminate = true;
thread.Join();
}
}

最佳答案

这是一个粗略的草图:

delegate void CompletedRequest(Request req);

class Processor : ITrackCompletion
{
//I need to maintain this list so that when the service stops I can cleanly close down
List<Request> requests = new List<Request>();

public void NewRequest(string data)
{
lock(requests)
request.Add(new Request(data), Complete);
}

public void Complete(Request req)
{
lock (requests)
requests.Remove(req);
}

public void Dispose()
{
//Cleanup each request
foreach (Request request in requests.ToArray())
{
request.Dispose();
}
}
}

class Request
{
Thread thread;
bool terminate;

public Request(string data, CompletedRequest complete)
{
try
{
while (true)
{
//Do some work
Thread.Sleep(1000);

if (doneWorking)
break;

if (terminate)
return;
}
}
finally
{
//We're done. If I return this thread stops. But how do I properly remove this Request instance from the Processor.requests list?
complete(this);
}
}

void Dispose()
{
terminate = true;
thread.Join();
}
}

关于c# - 使用线程正确处理类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1461996/

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