简体   繁体   中英

Is it viable to use await/async and threads simultaneously on one method?

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM