gpt4 book ai didi

c# - 使用队列创建 BackgroundWorker

转载 作者:太空狗 更新时间:2023-10-29 18:02:02 27 4
gpt4 key购买 nike

我需要创建队列并将其与 BackgroundWorker 一起使用。所以我可以添加操作,当一个操作完成时,下一步是在后台启动。我通过谷歌找到了这段代码:

public class QueuedBackgroundWorker<T>
{
public void QueueWorkItem(
Queue queue,
T inputArgument,
Func<T> doWork,
Action workerCompleted)
{
if (queue == null) throw new ArgumentNullException("queue");

BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = false;
bw.DoWork += (sender, args) =>
{
if (doWork != null)
{
args.Result = doWork(new DoWorkArgument<T>((T)args.Argument));
}
};
bw.RunWorkerCompleted += (sender, args) =>
{
if (workerCompleted != null)
{
workerCompleted(new WorkerResult<T>((T)args.Result, args.Error));
}
queue.Dequeue();
if (queue.Count > 0)
{
QueueItem<T> nextItem = queue.Peek() as QueueItem<T>;
nextItem.BackgroundWorker.RunWorkerAsync(nextItem.Argument);
}
};

queue.Enqueue(new QueueItem<T>(bw, inputArgument));
if (queue.Count == 1)
{
QueueItem<T> nextItem = queue.Peek() as QueueItem<T>;
nextItem.BackgroundWorker.RunWorkerAsync(nextItem.Argument);
}
}
}

public class DoWorkArgument<T>
{
public DoWorkArgument(T argument)
{
this.Argument = argument;
}
public T Argument { get; private set; }
}

public class WorkerResult<T>
{
public WorkerResult(T result, Exception error)
{
this.Result = result;
this.Error = error;
}

public T Result { get; private set; }
public Exception Error { get; private set; }
}

public class QueueItem<T>
{
public QueueItem(BackgroundWorker backgroundWorker, T argument)
{
this.BackgroundWorker = backgroundWorker;
this.Argument = argument;
}

public T Argument { get; private set; }
public BackgroundWorker BackgroundWorker { get; private set; }
}

但是我对 doWork 和 workerCompleted 有疑问。我收到错误:

Delegate 'Func' does not take 1 arguments

我该如何解决这个问题?我应该如何更改参数?谢谢

最佳答案

这是一个更短的方法,可以满足您的需求:

public class BackgroundQueue
{
private Task previousTask = Task.FromResult(true);
private object key = new object();
public Task QueueTask(Action action)
{
lock (key)
{
previousTask = previousTask.ContinueWith(t => action()
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.Default);
return previousTask;
}
}

public Task<T> QueueTask<T>(Func<T> work)
{
lock (key)
{
var task = previousTask.ContinueWith(t => work()
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.Default);
previousTask = task;
return task;
}
}
}

通过添加每个新 Action 作为前一个 Action 的延续,您可以确保一次只处理一个 Action ,因为下一个 Action 要等到上一个 Action 完成后才会开始,您可以确保没有线程闲置无事可做时闲置,并确保它们都按顺序完成。

另请注意,如果您认为只需要一个队列,而不是任何数量,则可以将所有成员设为static,但这取决于您。

关于c# - 使用队列创建 BackgroundWorker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15119974/

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