在 C# 3.0 中具有以下工作代码,如何将其转换为 C# 4.0 已替换该行
ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1));
经过
Task task1 = Task.Factory.StartNew(//?
?
工作 C# 3.0 控制台应用程序的完整代码:
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
var dict = new ConcurrentDictionary<int, string>();
ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1));
//???????
//Task task1 = Task.Factory.StartNew((Action)(LongGetOrAdd(dict, 1));
Console.WriteLine("Press enter to continue:");
foreach (var a in dict)
Console.WriteLine("dict.Key = {0} dict.Value = {1} ", a.Key, a.Value);
Console.ReadLine();
}
private static WaitCallback LongGetOrAdd(ConcurrentDictionary<int, string> dict, int index)
{
return o => dict.GetOrAdd
(index,
i =>
{
Console.WriteLine("From method LongGetOrAdd()!");
Thread.SpinWait(1000);
return i.ToString();
}
);
}
}
产生输出:
Press enter to continue:
From method LongGetOrAdd()!
dict.Key = 1 dict.Value = 1