0

在 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
4

2 回答 2

2

这应该做。

    var c = LongGetOrAdd(dict, 1);

    var t = Task.Factory.StartNew(() => c.Invoke(null));

    Task.WaitAll(task);
    Console.ReadLine();
于 2013-03-14T15:09:36.677 回答
0

您只需要更改LongGetOrAdd返回的委托类型并调用其他方法。

您还需要从 lambda 中删除参数,因为您实际上并没有传递任何信息。

只需查看Task.Factory.StartNew.

private static Action LongGetOrAdd(ConcurrentDictionary<int, string> dict, int index)
{
    return () => dict.GetOrAdd
    (index,
     i =>
     {
         Console.WriteLine("======!");
         Thread.SpinWait(1000);
         return i.ToString();
     }
    );
}
private static void Main()
{
    var dict = new ConcurrentDictionary<int, string>();
    Task.Factory.StartNew(LongGetOrAdd(dict, 1));

    Console.WriteLine();
    Console.WriteLine("press any key to exit . . .");
    Console.ReadKey();
}
于 2013-03-14T15:13:45.247 回答