c# - How to wait for a connection asynchronously? -
i've designed class wraps socket
, allows sending , receiving through/from it. since accepting, sending , receiving done through ui, don't want them block used asynchronous versions.
here's relevant code:
public void accept() { // ... // resultaccept iasyncresult resultaccept = listener.beginaccept(new asynccallback(acceptcallback), null); } private void acceptcallback(iasyncresult ar) { connectedsocket = listener.endaccept(ar); } public string receive() { char[] data = new char[128]; if (!resultaccept.iscompleted) // (1) resultaccept.asyncwaithandle.waitone(); connectedsocket.beginreceive(encoding.utf8.getbytes(data), 0, data.length, socketflags.none, new asynccallback(recvcallback), null); // ... }
when start receiving, since there's no connection yet, has wait 1 (1) , blocks ui (which, again, don't want).
in addition, when connection accepted nullreferenceexception
because when beginreceive
starts, acceptcallback
is, yes triggered, has not completed yet connectedsocket
still has initialized.
- why approach wrong?
- is possible achieve want async sockets?
- how can prevent ui blocking while waiting connection , ensuring validity of object?
- yes, because blocking. need throw away.
- yes, there
socket
extension methods on web adapt obsolete apm pattern tap pattern can use await. exercise becomes trivial then.
your code should like:
async task runserver() { socket serversocket = ...; while (true) { runconnection(await serversocket.acceptasync()); } }
and provide task runconnectionasync(socket s)
function async well. simple once leave obsolete apm pattern alone.
alternatively, use threads , synchronous io. nothing wrong doing that. await
little nicer, though, because marshals ui thread automatically.
Comments
Post a Comment