gpt4 book ai didi

c# - 比手动字典更好的选项来引用其中正在运行的方法的 'current task'?

转载 作者:行者123 更新时间:2023-11-30 13:04:16 24 4
gpt4 key购买 nike

注意:我并不是说这是一个的想法,只是想看看是否有比这个蛮力选择“更好”的选择。

这出现在之前的 SO 线程 @ How to get the current task reference?

但是,该线程受到特定接口(interface)的更多限制。

我快速组合起来的蛮力方法只使用弱引用字典。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetCurrentTaskExample
{
public static class TaskContext
{
// don't need a ConcurrentDictionary since we won't be reading/writing the same task id with different tasks concurrently
private static readonly Dictionary<int, WeakReference> s_indexedTaskReferences = new Dictionary<int, WeakReference>();

public static void AddAndStartTasks(IEnumerable<Task> tasks)
{
foreach (var task in tasks)
{
AddTask(task);
task.Start();
}
}

public static void AddTask(Task task)
{
s_indexedTaskReferences[task.Id] = new WeakReference(task);
}

public static Task GetCurrentTask()
{
var taskId = Task.CurrentId;
if (taskId == null) return null;

WeakReference weakReference;
if (s_indexedTaskReferences.TryGetValue(taskId.Value, out weakReference) == false) return null;
if (weakReference == null) return null; // should not happen since we don't store null as a value

var task = weakReference.Target as Task;
return task;
}
}

class Program
{
static void Main(string[] args)
{
var tasks = Enumerable.Range(0, 100)
.Select(i => new Task(VerifyCurrentTaskWorks, i))
.ToArray();

TaskContext.AddAndStartTasks(tasks);

Task.WaitAll(tasks);
}

static void VerifyCurrentTaskWorks(object instanceIdentifier)
{
var currentTask = TaskContext.GetCurrentTask();

if (currentTask.Id == Task.CurrentId)
{
Console.WriteLine("Verified for instance {0} that Task.CurrentId value of {1} matches Id property {2} of task {3}",
instanceIdentifier, Task.CurrentId, currentTask.Id, currentTask);
}
else
{
var errorMessage = String.Format("TaskContext.GetCurrentTask() failed for instance {0} with Task.CurrentId value of {1} and currentTask.Id value of {2}",
instanceIdentifier, Task.CurrentId, currentTask.Id);
throw new InvalidOperationException(errorMessage);
}
}
}
}

然而,这显然意味着创建任务的任何东西都被迫处理这种额外的麻烦,因此它不是很有用,尤其是 WRT C#5 异步方法,其中任务不是那么明确地创建。

同样,拥有需要它的代码可能不是一个好主意,因此将其视为更类似于思维练习。 :)

最佳答案

不幸的是,没有更好的方法,而且由于最终目标是关闭 Task.CurrentId,它实际上什至没有用,因为我们无法为异步方法获取“当前任务 ID” (在第一次等待之后,它已经返回给调用者)。

关于c# - 比手动字典更好的选项来引用其中正在运行的方法的 'current task'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9855978/

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