Reputation: 43
I'm new to multithreading and I have a (probably) simple question about using threads and await/async simultaneously. I have a method which reads a TCP stream, then processes the response it received. It's called in a fashion showed below:
ThreadStart ts = new ThreadStart(ReadTCP);
Thread tt = new Thread(ts);
Is it viable to read the data from the stream asynchronously? Like in this code:
private async void ReadTCP()
{
string responseData = string.Empty;
if(streamTCP.DataAvailable)
{
responseData = await readerTCP.ReadToEndAsync();
// some code handling the response
}
}
Code edited with MarioDS's help
Upvotes: 0
Views: 78
Reputation: 13063
Manually creating and manipulating threads is an advanced multithreading technique that requires a developer to really know what (s)he's doing (because memory fencing, synchronisation and marshalling between threads are all seriously advanced topics and easy to mess up). Thread-safety is hard.
If all you want is to improve responsiveness of your app, the async and await constructs that have been added to .NET a couple of years ago are perfect. They are not necessarily related to multithreading, as it is the underlying mechanism that decides whether new threads are created (and it's not always the case).
What you're doing is creating a thread and running the ReadTCP
method on that thread.
You can just as easily fix ReadTCP
so it returns Task
(async void
is really bad practice!) and then use it like this: var response = await ReadTCP();
in an async
method and it will give you what you want.
To run stuff in parallel while also running ReadTCP
, create a variable for the task and await
it later:
var readTask = ReadTCP();
DoOtherStuff();
AndMoreStuff();
AllAtOnce();
var response = await readTask;
DoSomethingWith(response);
By the way, you don't have to wrap async methods in Task.Run
. Instead of doing: Task.Run(() => FPXreaderTCP.ReadToEndAsync());
, just do await FPXreaderTCP.ReadToEndAsync()
.
Upvotes: 2