简体   繁体   中英

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?

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:

The thread will pause and wait for the called method to finish, and execute after completion

Note 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.

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