multithreading - C# : What Will Be The Greatest? Multiple Task or Single for One Job? -
i have code:
public async virtual void start(ipaddress ip, int port) { //start listening proccess listener = new tcplistener(ip, port); listener.start(); islistening = true; await task.run(async () => { while (islistening) { if (listener.pending()) { tcpclient client = await listener.accepttcpclientasync(); skyfilterclient sklient = new skyfilterclient(client); byte command = sklient.reader.readbyte(); if (command == (byte) skyfiltercommand.authenticate) { sklient = await authenticate(sklient); } else if(command == (byte)skyfiltercommand.register) { sklient = await register(sklient); } } } }); }
code @ program.cs, main method
new skyfiltercorelib.network.skyfilterserver().start(ipaddress.loopback, 7812); console.readline();
is best if have async lambda ? or use 1 task , let listener use listener.accepttcpclient
? 1 have best performance? thanks
it's not clear why you're creating task @ all. you're awaiting completion of task anyway, why not use:
listener = new tcplistener(ip, port); listener.start(); islistening = true; while (islistening) { if (listener.pending()) { var client = await listener.accepttcpclientasync(); // assume want client now... } }
in case wouldn't make difference if made bit synchronous - depends on whether want business of listening asynchronous operation in itself.
i think bigger question you're going client once you've accepted it. may want use asynchronous method handle client but not await result:
list<task> ongoingtasks = new list<task>(); ... var client = await listener.accepttcpclientasync(); ongoingtasks.add(handleclientasync(client));
then when want shut down, can wait ongoing tasks complete (possibly timeout) before let process die.
Comments
Post a Comment