0

I have class which implements an endless worker thread like this example, in my case representing a body. During runtime I will have between 0 and ~8 instances live at any time with instances constantly being created and destroyed.

Most of the time this class has a lifecycle of 30 seconds to 5 minutes but occasionally there may be a number of instances created and destroyed in a relatively short period of time. This is where I tend to run into performance issues given the low spec hardware this code is running on.

I would now like to rewrite the behavior so that I use a ThreadPool for my collection of running workers and I am struggling to find the correct way to structure the code.

Basically the code I have at the moment is something like

public class BodyCollection : IReadOnlyDictionary<ulong, TrackedBody>
{
    public void Update() 
    {
        if (createNew) 
        {
           var body = new TrackedBody();
           body.BeginTracking();
           this.Add(1234, body);
        }

        if (remove) 
        {
            TrackedBody body = this[1234];
            body.StopTracking();
            this.Remove(body);
        }
    }
}

public class TrackedBody
{
    private readonly Thread _BiometricsThread;
    private volatile bool _Continue = true;

    public TrackedBody() 
    {
        _BiometricsThread = new Thread(RunBiometricsThread);
    }

    public void BeginTracking()
    {
        _BiometricsThread.Start();
    }

    public void StopTracking() 
    {    
        _Continue = false;
    }

    private void RunBiometricsThread()
    {
        while(_Continue) 
        {
            System.Threading.Thread.Sleep(1000);
        }
    }
}

So how do I re-write the above to utilize a ThreadPool correctly and so that I can cancel running threads on the ThreadPool as required? Do I use CancellationTokens or ManualResetEvents to control the threads?

4

1 回答 1

1

我坚信您应该使用更现代的异步编程方法。我们将在这里使用任务并行库,因为它免费为您提供所需的功能:

  • 跟踪完成
  • 消除
  • 线程池

public class TrackedBody
{     
    public Task BeginTrackingAsync(CancellationToken cancellation)
    {
        return Task.Run(() => RunBiometricsThread(cancellation));
    }

    private void RunBiometricsThread(CancellationToken cancellation)
    {
        while(!cancellation.IsCancellationRequested) 
        {
            Task.Delay(1000, cancellation);
        }
    }
}

请注意,我已删除该async关键字。这本身什么也没做。

您可以使用该任务来跟踪正在进行的工作的状态。您可以使用取消令牌来停止所有工作。

于 2015-09-02T11:07:54.413 回答