C# Windows Phone 8.1 GetOutputStreamAsync(...) blocking after first use -
i'm trying create basic test app should:
1) broadcast "sometext" on port "1234"
2) wait second answers
3) return answers
while solution posted below works fine first time, every subsequent call blocks forever at:
stream = await socket.getoutputstreamasync(...)
till tried every possible way of cleaning (since thats suppose failure), wrapping in using(...) statements.
the problem occurs emulator hardware device using windows phone 8.1
thanks in advance!
the code start "discovery":
private void button_click(object sender, routedeventargs e) { pluginudp pudp = new pluginudp(); var task = pudp.scan("asf"); task.wait(); foreach (string s in task.result) output.text += s + "\r\n"; }
the code "discovery" itself:
using system; using windows.networking; using windows.networking.sockets; using windows.storage.streams; using system.text; using system.io; using system.threading.tasks; using system.collections.concurrent; using namespace whatever { public class pluginudp { private static readonly hostname broadcastaddress = new hostname("255.255.255.255"); private static readonly string broadcastport = "1234"; private static readonly byte[] data = encoding.utf8.getbytes("00wlan-ping00"); concurrentbag<string> receivers; public async system.threading.tasks.task<string[]> scan(string options) { receivers = new concurrentbag<string>(); receivers.add("ok"); datagramsocket socket = null; ioutputstream stream = null; datawriter writer = null; try { socket = new datagramsocket(); socket.messagereceived += messagereceived; await socket.bindservicenameasync(""); stream = await socket.getoutputstreamasync(broadcastaddress, broadcastport); writer = new datawriter(stream); writer.writebytes(data); await writer.storeasync(); task.delay(1000).wait(); } catch (exception exception) { receivers.add(exception.message); } { if (writer != null) { writer.detachstream(); writer.dispose(); } if(stream != null) stream.dispose(); if(socket != null) socket.dispose(); } return receivers.toarray(); ; } private async void messagereceived(datagramsocket socket, datagramsocketmessagereceivedeventargs args) { try { var result = args.getdatastream(); var resultstream = result.asstreamforread(1024); using (var reader = new streamreader(resultstream)) { var text = await reader.readtoendasync(); if (text.contains("pong")) { receivers.add(args.remoteaddress.tostring()); } } } catch (exception exception) { receivers.add("errcv"); } } } }
your problem starts here:
task.wait();
you're blocking on async code, leads deadlock.
you want:
private async void button_click(object sender, routedeventargs e) { pluginudp pudp = new pluginudp(); string[] result = await pudp.scan("asf"); foreach (string s in result) output.text += s + "\r\n"; }
you want do:
await task.delay(1000);
instead of:
task.delay(1000).wait();
Comments
Post a Comment