以下の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