Quantcast
Channel: Questions in topic: "webrequest"
Viewing all articles
Browse latest Browse all 387

Wait for value to not be null until thread finishes

$
0
0
Hey, how can I start a thread and wait until a string is not null/empty to return it? I'm calling a static string from another class, this starts a new thread that gets the response from the server and assigns it to a string. The problem is that the answer is returned before the thread does its job. I've thought about coroutines but I don't see a way of returning values directly. If anyone has any tips on how this should be done or any methods to follow I'm all ears. Here's the code: private static Thread sendAndReceiveDataThread; private static Networking Instance; private void Awake() { Instance = this; } private static string answer; public static string SendAndReceive(string data) { sendAndReceiveDataThread = new Thread(() => Instance.SendAndReceiveData(data)); sendAndReceiveDataThread.Start(); return answer; } private void SendAndReceiveData(string data) { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] bytes = encoding.GetBytes(data); WebRequest request = WebRequest.Create(server); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; Stream stream = request.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); stream.Close(); WebResponse response = request.GetResponse(); stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); answer = sr.ReadToEnd(); stream.Close(); sr.Close(); request.Abort(); sendAndReceiveDataThread.Abort(); }

Viewing all articles
Browse latest Browse all 387

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>