I want to generate List<Task>
and then call it all parallel. I try to do this, but not understood how pass index in lambda expression. In my realisation always send last index of for
. But i want to use all indexes in parallel computing...
List<Task> tasks = new List<Task>();
var valueSize = Values.Count;
for (int i = 1; i <= valueSize; i++)
{
tasks.Add(Task.Factory.StartNew(
() => {
this.Values[i] = this._tcpRepository.GetValueAsync(i).ToString().GetInt32();
}));
}
Task.WaitAll(tasks.ToArray());
Additional information:
public Dictionary<int, int> Values { get; set; }
In TcpRepository
public async Task<string> GetValueAsync(int digit)
{
var netStream = this.TcpClient.GetStream();
if (netStream.CanWrite)
{
Byte[] sendBytes = Encoding.UTF8.GetBytes(digit.ToString());
await netStream.WriteAsync(sendBytes, 0, sendBytes.Length);
}
if (netStream.CanRead)
{
byte[] bytes = new byte[this.Client.ReceiveBufferSize];
await netStream.ReadAsync(bytes, 0, (int)this.Client.ReceiveBufferSize);
return bytes.ToString();
}
return null;
}
GetInt32()
it's my custom extension for string public static int GetInt32(this string value)
. Strings can come with garbage as characters that are not numbers.