简体   繁体   English

在一种方法中同时使用等待/异步和线程是否可行?

[英]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. 我有一个读取TCP流,然后处理它收到的响应的方法。 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 MarioDS的帮助下编辑的代码

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. 如果您想要的只是提高应用程序的响应能力,那么几年前已添加到.NET的async和await构造是完美的。 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. 您正在做的是创建一个线程并在该线程上运行ReadTCP方法。

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(); 您可以轻松地修复ReadTCP ,使其返回Taskasync void确实是一种不好的做法!),然后像这样使用它: var response = await ReadTCP(); in an async method and it will give you what you want. async方法中,它将为您提供所需的内容。

To run stuff in parallel while also running ReadTCP , create a variable for the task and await it later: 要在同时运行ReadTCP同时并行运行东西,请为任务创建一个变量,然后await它:

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 . 顺便说一下,您不必在Task.Run包装异步方法。 Instead of doing: Task.Run(() => FPXreaderTCP.ReadToEndAsync()); 而不是这样做: Task.Run(() => FPXreaderTCP.ReadToEndAsync()); , just do await FPXreaderTCP.ReadToEndAsync() . ,只需await FPXreaderTCP.ReadToEndAsync()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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