before I start I just want to say that I was looking for solution of this problem for a very long time and I didn't find anything that could help me to solve it.
I need to connect to some server, send a message and display result. It's pretty easy, but it crashes and I have not idea why.
Here is code
private async void startMeasurementButton_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Reading start");
socket = new StreamSocket();
var hostName = new HostName("192.168.10.20");
await socket.ConnectAsync(hostName, "10000");
dataReader = new DataReader(socket.InputStream);
dataWriter = new DataWriter(socket.OutputStream);
dataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
dataReader.ByteOrder = ByteOrder.LittleEndian;
dataReader.InputStreamOptions = InputStreamOptions.Partial;
isReading = true;
await Task.Run(() =>
{
Read();
});
}
This works just fine, it connects to server and is ready to work with. And not there is second method
private async Task Read()
{
while (isReading)
{
try
{
dataWriter.WriteString("1");
await dataWriter.StoreAsync(); // <== here an exception occurs
await dataWriter.FlushAsync();
dataWriter.DetachStream();
IAsyncOperation<uint> taskLoad = dataReader.LoadAsync(8196);
taskLoad.AsTask().Wait();
uint bytesToRead = taskLoad.GetResults();
reading1Voltage.Text = bytesToRead.ToString();
}
catch (Exception e)
{
Debug.WriteLine("Error: " + e.Message);
}
}
}
In selected line code crashes and throws "Operation identifier is not valid". I tried to do the same thing I did with LoadAsync
IAsyncOperation<uint> taskLoad = dataReader.LoadAsync(8196);
taskLoad .AsTask().Wait();
but it doesn't work. reading1Voltage is XAML control, TextBox.
What is wrong with this code and how can I make it work?