gpt4 book ai didi

c# - 需要工作线程方法的模板

转载 作者:行者123 更新时间:2023-12-02 05:38:51 25 4
gpt4 key购买 nike

我需要设计完美的工作线程方法。该方法必须执行以下操作:

  • 1)从队列中提取一些内容(假设是一个字符串队列)并执行一些操作
  • 2)下课后 parking 返回
  • 3)等待某个事件(队列不为空)并且不消耗CPU
  • 4)在单独的线程中运行

主线程会将字符串添加到队列中,并向线程方法发出信号以继续执行工作。

我希望您向我提供包含所需同步对象的模板。

class MyClass, IDisposable
{
// Thread safe queue from third party
private ThreadSafeQueue<string> _workerQueue;
private Thread _workerThread;

public bool Initialize()
{
_workerThread = new Thread(WorkerThread).Start();
}

public AddTask(string object)
{
_workerQueue.Enqueue(object);
// now we must signal worker thread
}

// this is worker thread
private void WorkerThread()
{
// This is what worker thread must do
List<string> objectList = _workerQueue.EnqueAll
// Do something
}

// Yeap, this is Dispose
public bool Dispose()
{
}
}

最佳答案

尝试这样的事情。使用字符串类型实例化并给它一个委托(delegate)来处理您的字符串:

    public class SuperQueue<T> : IDisposable where T : class
{
readonly object _locker = new object();
readonly List<Thread> _workers;
readonly Queue<T> _taskQueue = new Queue<T>();
readonly Action<T> _dequeueAction;

/// <summary>
/// Initializes a new instance of the <see cref="SuperQueue{T}"/> class.
/// </summary>
/// <param name="workerCount">The worker count.</param>
/// <param name="dequeueAction">The dequeue action.</param>
public SuperQueue(int workerCount, Action<T> dequeueAction)
{
_dequeueAction = dequeueAction;
_workers = new List<Thread>(workerCount);

// Create and start a separate thread for each worker
for (int i = 0; i < workerCount; i++)
{
Thread t = new Thread(Consume) { IsBackground = true, Name = string.Format("SuperQueue worker {0}",i )};
_workers.Add(t);
t.Start();

}

}


/// <summary>
/// Enqueues the task.
/// </summary>
/// <param name="task">The task.</param>
public void EnqueueTask(T task)
{
lock (_locker)
{
_taskQueue.Enqueue(task);
Monitor.PulseAll(_locker);
}
}

/// <summary>
/// Consumes this instance.
/// </summary>
void Consume()
{
while (true)
{
T item;
lock (_locker)
{
while (_taskQueue.Count == 0) Monitor.Wait(_locker);
item = _taskQueue.Dequeue();
}
if (item == null) return;

// run actual method
_dequeueAction(item);
}
}

/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
// Enqueue one null task per worker to make each exit.
_workers.ForEach(thread => EnqueueTask(null));

_workers.ForEach(thread => thread.Join());

}
}

关于c# - 需要工作线程方法的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4022976/

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