简体   繁体   English

使用异步线程?

[英]Threading With Async?

Ok so below is my code for a server related program I am working on. 好的,下面是我正在处理的服务器相关程序的代码。 It's pretty bare at the current moment but I intend to kick start development as soon as I can sort of this threading stuff perfectly. 目前还很裸露,但我打算尽快开始完善此线程工作,然后开始开发。

Today the question I have about threading relates to the usefulness of of the bottom segment of the below code. 今天,我有关线程的问题与以下代码底部的有用性有关。

If the only loop I have going is the loop in StartListening and in the constructor for this class I make a instance of a Thread (to my understanding is the same as creating a task with TaskCreationOptions.LongRunning, I know task is better but really I don't need any features of a task I just need a thread outside of threadpool) and my main thread/ui thread calls this constructor (which makes a thread) then is there a point for me to async my StartListening? 如果我唯一要进行的循环是StartListening中的循环,并且在此类的构造函数中,我将创建一个Thread的实例(据我了解,这与使用TaskCreationOptions.LongRunning创建任务相同,我知道任务会更好,但实际上我不需要任务的任何功能,我只需要一个线程池之外的线程),而我的主线程/ ui线程调用此构造函数(该线程构成一个线程),那么我有一个异步StartListening的意义吗?

To my understanding async and await allow the main thread to do its thing when we wait in this loop. 据我了解,异步和等待允许主线程在我们在此循环中等待时执行其操作。 But since this is running on it's own thread is there a point for me to async it anymore? 但是由于这是在它自己的线程上运行的,所以我还有一点要异步化吗?

ConnectionThread = new Thread(StartListening);
ConnectionThread.Name = "Connection Handle";
ConnectionThread.Start();

-------------------------- above this is the top segment ------------------------- --------------------------这是最重要的部分------------------ -------

public async void StartListening()
{
    listener = new TcpListener(15111);
    listener.Start();

    try
    {

        while (running)
        {
            TcpClient tcpclient = await listener.AcceptTcpClientAsync();
            Client client = new Client(tcpclient, ((IPEndPoint)tcpclient.Client.RemoteEndPoint).Address.ToString());
            Task handshakeTask = Task.Factory.StartNew(() => {
                ClientHandle.AddToClientPool(client);
                SendRequestInformation(client, 1);
            });
        }

    }
    catch (Exception e)
    {
        if (MainWindow.debugWindow != null)
            MainWindow.mainWindowDispacter.BeginInvoke(SendDebugMessage, new Object[] { e.ToString() });
        else
            Console.WriteLine(e.ToString());
    }
}

And since I am here already, I am currently using, 由于我已经在这里,所以我目前正在使用,

Byte[] buffer = new byte[4068];
var AmountRead =  await stream.ReadAsync(buffer, 0, buffer.Length, cts);

To get messages from the client. 从客户端获取消息。 It seems like I get too much data as the byte size is too big. 字节大小太大,似乎获得了太多数据。 So then I tried. 因此,我尝试了。

var AmountRead =  await stream.ReadAsync(buffer, 0, t.getClientSocket().ReceiveBufferSize, cts);

and didn't seem to work. 而且似乎没有用。 Any clues? 有什么线索吗?

Quote: 引用:

is there a point for me to async it anymore 我有一点要再异步了吗

To answer your question, yes it does make sense, specially if you want a process on that thread to be non-blocking on the thread. 要回答您的问题,是的,这确实有意义,特别是如果您希望该线程上的进程在该线程上是非阻塞的。 To point it out in your code. 在您的代码中指出。

while (running)
{
    TcpClient tcpclient = await listener.AcceptTcpClientAsync(); // NOTE 1 Below
    Client client = new Client(tcpclient, 
        ((IPEndPoint)tcpclient.Client.RemoteEndPoint).Address.ToString());
    Task handshakeTask = Task.Factory.StartNew(() => // NOTE 2 Below
    {
        ClientHandle.AddToClientPool(client);
        SendRequestInformation(client, 1);
    });
}

Note 1: 注1:

The thread will pause and wait for the called method to finish, and execute after completion 线程将暂停并等待调用的方法完成,并在完成后执行

Note 2: 笔记2:

It will execute asynchronously from the called async method. 它将从调用的异步方法异步执行。 So the Thread you created will continue the loop after that codeblock because it's executed in another thread. 因此,您创建的线程将在该代码块之后继续循环,因为它是在另一个线程中执行的。

So if you want your thread to execute faster and you dont need the response of the asynchronously started method from the thread then it makes sense. 因此,如果您希望线程执行得更快,并且不需要线程异步启动方法的响应,那么它就很有意义。

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

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