奇怪,好像有什么毛病。NET(C#?),将参数编组到工作线程。
struct MyPair<TKey, TValue> : IConvertable
{
public readonly TKey Key;
public readonly TValue Value;
public MyPair(TKey key, TValue value)
{
Key = key;
Value = value;
}
// I just used the smart-tag on IConvertable to get all these...
// public X ToX(IFormatProvider provider) { throw new InvalidCastException(); }
...
public object ToType(Type conversionType, IFormatProvider provider)
{
if (typeof(MyPair<TKey, TValue>).GUID == conversionType.GUID)
return this;
throw new InvalidCastException();
}
}
var data = new Dictionary<string, string> {
{ "Hello", "World" },
{ "How are", "You?" },
{ "Goodbye", "World!" }
};
foreach (var pair in data)
{
var copy = pair; // define a different variable for each worker
Action worker = () => Console.WriteLine("Item {0}, {1}", copy.Key, copy.Value);
worker.BeginInvoke(null, null);
}
当然,如果你需要结果,你需要在另一个方向上存储IAsyncResults,它可能与参数有同样的问题。作为替代方案,您可以在它们完成时将它们添加到集合中,但锁定有点奇怪:
var data = new Dictionary<string, string> {
{ "Hello", "World" },
{ "How are", "You?" },
{ "Goodbye", "World!" }
};
var results = new List<KeyValuePair<string, string>>();
var pending = 0;
var done = new ManualResetEvent(false);
var workers = new List<Action>();
foreach (var pair in data)
{
++pending;
var copy = pair; // define a different variable for each worker
workers.Add(delegate()
{
Console.WriteLine("Item {0}, {1}", copy.Key, copy.Value);
lock (results)
results.Add(new KeyValuePair<string, string>("New " + copy.Key, "New " + copy.Value));
if (0 == Interlocked.Decrement(ref pending))
done.Set();
});
}
foreach (var worker in workers)
worker.BeginInvoke(null, null);
done.WaitOne();
foreach (var pair in results)
Console.WriteLine("Result {0}, {1}", pair.Key, pair.Value);