I'm programming with Tasks and await/async. I assumed that the multithreading works like it does in NodeJS or Python, that is, it doesn't, everything just runs on the same thread. But I've been trying to learn how Tasks actually get executed and my understanding is that they're executed by TaskScheduler.Default who's implementation is hidden but can be expected to use a ThreadPool.
Should I be programming as if all my Tasks can run in any thread?
The extent of my asynchronous programming is fairly lightweight CPU work consisting of several infinite loops that do work and then await on Task.Delay for several seconds. Right now the only shared resources is an int that increments every time I write a network message but in the future I expect my tasks will be sharing Dictionaries and Lists.
I also have a network Task that connects to a TCP server and reads messages using a Task I implemented on BeginRead+EndRead. The Read function is called by an infinite loop that reads a messages, processes it, then reads a new message.
void OnRead(IAsyncResult result)
{
var pair = (Tuple<TaskCompletionSource<int>, NetworkStream>)result.AsyncState;
int count = pair.Item2.EndRead(result);
pair.Item1.SetResult(count);
}
async Task<byte[]> Read(NetworkStream stream, uint size)
{
var result = new byte[size];
var count = 0;
while(count < size)
{
var tcs = new TaskCompletionSource<int>();
stream.BeginRead(result, count, result.Length - (int)count, new AsyncCallback(OnRead), Tuple.Create(tcs, stream));
count += await tcs.Task;
}
return result;
}
I write to the NetworkStream using synchronous writes.