I have simple Windows service which sends HTTP requests on few timer's. I installed Release version of this service and after few days running of it I noticed memory usage increase from ~5MB to ~32MB. This made me worried, I rarely do anything for desktop so I really lack knowledge to figure out where leak is happening...
Maybe log4net object is growing?
Here I initialize my service and it's configuration:
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Historian historian;
private EndpointsConfiguration endpointsConfiguration;
private readonly string endpointsJson;
public Service()
{
InitializeComponent();
historian = new Historian(ConfigurationManager.ConnectionStrings["Historian"].ConnectionString);
try
{
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
endpointsJson = File.ReadAllText($#"{path}\EndpointsConfiguration.json");
var jsonOptions = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
}
};
endpointsConfiguration = JsonSerializer.Deserialize<EndpointsConfiguration>(endpointsJson, jsonOptions);
}
catch (Exception ex)
{
logger.Fatal("Nepavyko nuskaityti konfigūracijos", ex);
return;
}
}
OnStart method:
protected override void OnStart(string[] args)
{
logger.Info("Servisas startavo");
try
{
historian.Ping();
logger.Info("Pavyko prisijungti prie Historian duomenų bazės");
foreach (var endpoint in endpointsConfiguration.Endpoints)
{
var timer = new TimerWithContext(endpoint, endpoint.Interval)
{
Enabled = true
};
timer.Elapsed += async (sender, e) => await Timer_Elapsed(sender, e);
}
logger.Info("Suformuotos užduočių gijos");
}
catch (Exception ex)
{
logger.Fatal("Nepavyko prisijungti prie Historian duomenų bazės", ex);
OnStop();
}
}
Timer Elapsed (primary work of this service):
private async Task Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Endpoint endpoint = ((TimerWithContext)sender).Endpoint;
var endpointTags = endpoint.Tags;
try
{
historian.RetrieveLiveValues(ref endpointTags);
}
catch (Exception ex)
{
logger.Fatal($"Nepavyko nuskaityti naujausių tag'o reikšmių, Gavėjas:${endpoint.UrlAddress}", ex);
}
finally
{
using (HttpClient httpClient = new HttpClient())
{
if (endpoint.AuthScheme != null && endpoint.AuthKey != null)
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(endpoint.AuthScheme, endpoint.AuthKey);
}
object data = new { };
switch (endpoint.SerializationOption)
{
case SerializationOption.PECustom:
data = new DeviceComponents
{
SerialNr = endpoint.SerialNr,
MeterCode = endpoint.MeterCode,
ReadDate = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}",
DevCompValues = endpointTags.ToDictionary(tag => tag.DestinationName, tag => tag.Value.ToString())
};
break;
default:
data = endpointTags.ToDictionary(tag => tag.DestinationName, tag => tag.Value.ToString());
break;
}
var content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
try
{
var response = await httpClient.PostAsync(endpoint.UrlAddress, content);
response.EnsureSuccessStatusCode();
logger.Info($"Duomenys perduoti gavėjui:{endpoint.Name}");
}
catch (Exception ex)
{
logger.Warn($"Nepavyko perduoti duomenų šaltiniui: {endpoint.Name}; Adresas{endpoint.UrlAddress}; Duomenų kiekis:{endpoint.Tags.Count}", ex);
}
}
}
}
Related
I'm using QR Code Scanner in Xamarin App, when it scans the qr code, there are some operation it does which takes about a minute, while it's performing operation, I want to show a loading dialog on the screen. But, it isn't showing on the screen, and elsewhere in the app, it's working perfectly.
Code
var expectedFormat = ZXing.BarcodeFormat.QR_CODE;
var opts = new ZXing.Mobile.MobileBarcodeScanningOptions { PossibleFormats = new List<ZXing.BarcodeFormat> { expectedFormat } };
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan(opts);
if (result == null)
{
// code
return null;
}
else
{
using (UserDialogs.Instance.Loading("Processing"))
{
// code
}
}
UPDATE CODE SAMPLE
public async Task Verification(object sender, EventArgs e)
{
try
{
var expectedFormat = ZXing.BarcodeFormat.QR_CODE;
var opts = new ZXing.Mobile.MobileBarcodeScanningOptions { PossibleFormats = new List<ZXing.BarcodeFormat> { expectedFormat } };
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan(opts);
if (result == null)
{
// Code
return null;
}
else
{
try
{
// QR Scan Result
string qr_scan = result.Response;
var result = JsonConvert.DeserializeObject<QRScan>(qr_scan);
await CreateConnection();
}
catch (Exception error)
{ }
finally
{
// navigate to next page
await NavigationService.NavigateToAsync<NextViewModel>();
}
}
}
catch (Exception error)
{ }
return null;
}
public async Task CreateConnection()
{
UserDialogs.Instance.Loading("Processing");
if ()
{
try
{
// Code
}
catch (Exception error)
{
// Code
}
finally
{
await CreateFolder(default, default);
}
}
}
public async Task CreateFolder(object sender, EventArgs e)
{
UserDialogs.Instance.Loading("Processing");
try
{
// Code
}
catch (Exception error)
{
// Code
}
return null;
}
You can use Xamarin.Essentials' MainThread class and more specifically - the InvokeOnMainThreadAsync method. The idea of this method is to not only execute a code on the UI/main thread, but to also to await it's code. This way you can have both async/await logic and main thread execution.
try
{
// QR Scan Result
string qr_scan = result.Response;
var result = JsonConvert.DeserializeObject<QRScan>(qr_scan);
await MainThread.InvokeOnMainThreadAsync(() => CreateConnection());
}
catch (Exception error)
{ }
finally
{
// navigate to next page
await NavigationService.NavigateToAsync<NextViewModel>();
}
Keep in mind that if the method CreateConnection takes a long time to execute, then it would be better to execute on the main thread only the dialog presentation (UserDialogs.Instance.Loading("")).
Try something like this
Device.BeginInvokeOnMainThread(async () =>
{
try
{
using (UserDialogs.Instance.Loading(("Processing")))
{
await Task.Delay(300);
//Your Service code
}
}
catch (Exception ex)
{
var val = ex.Message;
UserDialogs.Instance.Alert("Test", val.ToString(), "Ok");
}
});
We have a siglnalR hub hosted in IIS, and a WPF .net core application that connects. Everything is working perfectly on first run. However, when IIS recycles the application pool, the WPF client re-reconnects successfully, but, (so it seems) on another thread, as when the user attempts to perform an action (open a new WPF window) - the following error is thrown when creating a new instance of the window to open :-
"The calling thread must be STA, because many UI components require this"
This is how we connect to the hub :-
private async void Connect()
{
try
{
_signalRConnection.On<Notification>(NotificationMessageStr, (message) =>
{
if (message != null && _signalRConnection != null)
{
OnProcessMessage(message);
}
}
);
_signalRConnection.Reconnecting += error =>
{
OnReconnecting("Connection lost - Attempting to reconnect.");
return Task.CompletedTask;
};
_signalRConnection.Reconnected += connectionId =>
{
OnReconnected("Reconnected");
return Task.CompletedTask;
};
_signalRConnection.Closed += error =>
{
OnLostConnection("Failed to connect");
// Notify users the connection has been closed or manually try to restart the connection.
return Task.CompletedTask;
};
try
{
//Connect to the server
await _signalRConnection.StartAsync();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
When a message is received from the hub, we call :-
private void SubscriveToNewNotification()
{
vm.NewNotification += (sender, e) => {
ShowNotificationAlert(e.NotificationMessage); };
}
private void ShowNotificationAlert(Notification notification) {
NotificationAlert notificationAlert = new NotificationAlert();
notificationAlert.notification = notification;
notificationAlert.Show();
}
And it is this:-
NotificationAlert notificationAlert = new NotificationAlert();
That is failing.
This is how the connection is built up :-
private void InitializeViewModel()
{
try
{
string serviceAddress = "xxxx/notificationHub";
connectHub = NotificationHubManager.CreateNotificationHub(serviceAddress, userInfo);
}
catch (System.Exception ex)
{
System.Windows.MessageBox.Show(ex.Message + "--");
}
connectHub.ProcessMessage += (sender, e) =>
{
// THIS IS WHERE IT FALLS OVER
NotificationAlert n = new NotificationAlert();
OnNotificationReceived(e.NotificationMessage);
};
-- This is the notification hub
public static NotificationHubConnect CreateNotificationHub(string address, ISwiftUser userInfo = null)
{
HubConnection hubConnection = new HubConnectionBuilder()
.WithUrl(address)
.WithAutomaticReconnect()
.Build();
try
{
var result = new NotificationHubConnect(hubConnection, userInfo);
return result;
}
catch (Exception ex)
{
throw ex;
}
}
Is there a way to have the reconnect run on the same thread?
It is my first program on wifi direct so I made a simple program that just discover all nearby devices and then try to connect to one of them the discovery works fine and gets all the devices the problem is in the connection that always fails after using this function WiFiDirectDevice.FromIdAsync() it keeps paring for too long and then it fails always.
I was following the code on this microsoft tutorial: https://channel9.msdn.com/Events/Build/2015/3-98
Here is my code:
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App7
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
DeviceInformationCollection DevicesFound;
WiFiDirectAdvertisementPublisher pub;
WiFiDirectConnectionListener listener;
CancellationTokenSource m_CancellationTokenSource;
private async void button_Click(object sender, RoutedEventArgs e)
{
String DeviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
DevicesFound = await DeviceInformation.FindAllAsync(DeviceSelector);
if(DevicesFound.Count>0)
{
connectedDeviceslist.ItemsSource = DevicesFound;
var dialog = new MessageDialog(DevicesFound[0].Name);
await dialog.ShowAsync();
}
}
private async void button1_Click(object sender, RoutedEventArgs e)
{
int selectedIndex = connectedDeviceslist.SelectedIndex;
String deviceID = DevicesFound[selectedIndex].Id;
var selecetedDevice = DevicesFound[selectedIndex];
try
{
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = Convert.ToInt16("1");
connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
m_CancellationTokenSource = new CancellationTokenSource();
var wfdDevice = await WiFiDirectDevice.FromIdAsync(selecetedDevice.Id, connectionParams).AsTask(m_CancellationTokenSource.Token);
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
}
catch(Exception ex)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
});
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
pub = new WiFiDirectAdvertisementPublisher();
pub.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
listener = new WiFiDirectConnectionListener();
listener.ConnectionRequested += OnConnectionRequested;
pub.Start();
}
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
try
{
var ConnectionRequest = args.GetConnectionRequest();
var tcs = new TaskCompletionSource<bool>();
var dialogTask = tcs.Task;
var messageDialog = new MessageDialog("Connection request received from " + ConnectionRequest.DeviceInformation.Name, "Connection Request");
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand("Accept", null, 0));
messageDialog.Commands.Add(new UICommand("Decline", null, 1));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 1;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
// Show the message dialog
var commandChosen = await messageDialog.ShowAsync();
tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
});
var fProceed = await dialogTask;
if (fProceed == true)
{
var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
var wfdDeviceTask = tcsWiFiDirectDevice.Task;
// WriteToOutput("Connecting to " + ConnectionRequest.DeviceInformation.Name + "...");
WiFiDirectConnectionParameters ConnectionParams = new WiFiDirectConnectionParameters();
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
try
{
ConnectionParams.GroupOwnerIntent = 14;
tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id, ConnectionParams));
}
catch (Exception ex)
{
// WriteToOutput("FromIdAsync task threw an exception: " + ex.ToString());
}
});
WiFiDirectDevice wfdDevice = await wfdDeviceTask;
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
/* m_ConnectedDevices.Add("dummy", wfdDevice);
WriteToOutput("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() + " Port: " + Globals.strServerPort);
StreamSocketListener listenerSocket = new StreamSocketListener();
listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);*/
}
else
{
/* // Decline the connection request
WriteToOutput("Connection request from " + ConnectionRequest.DeviceInformation.Name + " was declined");
ConnectionRequest.Dispose();*/
}
}
catch (Exception ex)
{
//WriteToOutput("FromIdAsync threw an exception: " + ex.ToString());
}
}
}
}
I've got an intra-PC communication server / client set up to send and receive data from one program to another - in this case, a custom server that is listening to text commands and Unity3D.
For the most part, it works, however every once in awhile, it will drop packets, and Unity will not get them without multiple attempts. The packets seem to be sent but lost, as I do see the "Sent message" console log. The following is the code for the server and client:
SERVER:
class TCPGameServer
{
public event EventHandler Error;
public Action<Data> ADelegate;
TcpListener TCPListener;
TcpClient TCPClient;
Client ActiveClient;
NetworkStream networkStream;
StreamWriter returnWriter;
StreamReader streamReader;
Timer SystemTimer = new Timer();
Timer PingTimer = new Timer();
int Port = 8637;
public TCPGameServer()
{
TCPListener = new TcpListener(IPAddress.Loopback, Port);
SystemTimer.Elapsed += StreamTimer_Tick;
SystemTimer.AutoReset = true;
SystemTimer.Interval = 2000;
PingTimer.Elapsed += PingTimer_Tick;
PingTimer.AutoReset = true;
PingTimer.Interval = 30000;
}
public void OpenListener()
{
TCPListener.Start();
TCPListener.BeginAcceptTcpClient(AcceptTCPCallBack, null);
Console.WriteLine("Network Open.");
}
public void GameLogout()
{
SystemTimer.AutoReset = false;
SystemTimer.Stop();
PingTimer.AutoReset = false;
PingTimer.Stop();
ActiveClient = null;
returnWriter.Dispose();
streamReader.Dispose();
Console.WriteLine("The client has logged out successfully.");
}
private void AcceptTCPCallBack(IAsyncResult asyncResult)
{
TCPClient = null;
ActiveClient = null;
returnWriter = null;
streamReader = null;
try
{
TCPClient = TCPListener.EndAcceptTcpClient(asyncResult);
TCPListener.BeginAcceptTcpClient(AcceptTCPCallBack, null);
ActiveClient = new Client(TCPClient);
networkStream = ActiveClient.NetworkStream;
returnWriter = new StreamWriter(TCPClient.GetStream());
streamReader = new StreamReader(TCPClient.GetStream());
Console.WriteLine("Client Connected Successfully.");
Data Packet = new Data();
Packet.cmdCommand = Command.Login;
Packet.strName = "Server";
Packet.strMessage = "LOGGEDIN";
SendMessage(Packet);
SystemTimer.AutoReset = true;
SystemTimer.Enabled = true;
SystemTimer.Start();
Ping();
PingTimer.AutoReset = true;
PingTimer.Enabled = true;
PingTimer.Start();
} catch (Exception ex)
{
OnError(TCPListener, ex);
return;
}
}
private void StreamTimer_Tick(object source, System.Timers.ElapsedEventArgs e)
{
CheckStream();
}
private void PingTimer_Tick(object source, System.Timers.ElapsedEventArgs e)
{
Ping();
}
private void Ping()
{
if (TCPClient.Connected)
{
Data Packet = new Data();
Packet.cmdCommand = Command.Ping;
Packet.strName = "Server";
Packet.strMessage = "PING";
SendMessage(Packet);
}
}
public void CheckStream()
{
try
{
if (TCPClient.Available > 0 || streamReader.Peek() >= 0)
{
string PacketString = streamReader.ReadLine();
Data packet = JsonConvert.DeserializeObject<Data>(PacketString);
switch (packet.cmdCommand)
{
case Command.Logout:
GameLogout();
break;
case Command.Message:
if (ADelegate != null)
{
ADelegate(packet);
}
break;
case Command.Ping:
Console.WriteLine("PONG!");
break;
}
}
} catch (IOException e)
{
Console.WriteLine(e.Message);
} catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
}
}
public void SendMessage(Data packet)
{
if (ActiveClient != null)
{
string packetMessage = JsonConvert.SerializeObject(packet);
returnWriter.WriteLine(packetMessage);
returnWriter.Flush();
}
}
public void OnError(object sender, Exception ex)
{
EventHandler handler = Error;
if (handler != null)
{
ErrorEventArgs e = new ErrorEventArgs(ex);
handler(sender, e);
}
}
public void RegisterActionDelegate(Action<Data> RegisterDelegate)
{
ADelegate += RegisterDelegate;
}
public void UnRegisterActionDelegate(Action<Data> UnregisterDelegate)
{
ADelegate -= UnregisterDelegate;
}
}
CLIENT:
public class TCPNetworkClient
{
public Action<Data> PacketDelegate;
public TcpClient TCPClient;
int Port = 8637;
StreamReader streamReader;
StreamWriter streamWriter;
Timer StreamTimer = new Timer();
public bool LoggedIn = false;
public void Start()
{
if (LoggedIn == false)
{
TCPClient = null;
StreamTimer.AutoReset = true;
StreamTimer.Interval = 2000;
StreamTimer.Elapsed += StreamTimer_Tick;
try
{
TCPClient = new TcpClient("127.0.0.1", Port);
streamReader = new StreamReader(TCPClient.GetStream());
streamWriter = new StreamWriter(TCPClient.GetStream());
StreamTimer.Enabled = true;
StreamTimer.Start();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
}
private void StreamTimer_Tick(System.Object source, System.Timers.ElapsedEventArgs e)
{
if (TCPClient.Available > 0 || streamReader.Peek() >= 0)
{
string PacketString = streamReader.ReadLine();
Data packet = JsonConvert.DeserializeObject<Data>(PacketString);
PacketDelegate(packet);
}
}
public void Logout()
{
Data Packet = new Data();
Packet.cmdCommand = Command.Logout;
Packet.strMessage = "LOGOUT";
Packet.strName = "Game";
SendMessage(Packet);
if (streamReader != null && streamWriter != null)
{
streamReader.Dispose();
streamWriter.Dispose();
TCPClient.Close();
TCPClient = null;
streamReader = null;
streamWriter = null;
}
StreamTimer.Stop();
}
public void SendMessage(Data packet)
{
string packetMessage = JsonConvert.SerializeObject(packet);
try
{
streamWriter.WriteLine(packetMessage);
streamWriter.Flush();
} catch (Exception e)
{
}
}
public void RegisterActionDelegate(Action<Data> RegisterDelegate)
{
PacketDelegate += RegisterDelegate;
}
public void UnRegisterActionDelegate(Action<Data> UnregisterDelegate)
{
PacketDelegate -= UnregisterDelegate;
}
}
I'm not really sure what's going on, or if there are any more additional checks that I need to add into the system. Note: It's TCP so that "when" this fully works, I can drop the client into other programs that I might write that may not fully rely or use Unity.
new TcpClient("127.0.0.1", Port) is not appropriate for the client. Just use TcpClient(). There is no need to specify IP and port, both of which will end up being wrong.
TCPClient.Available is almost always a bug. You seem to assume that TCP is packet based. You can't test whether a full message is incoming or not. TCP only offers a boundaryless stream of bytes. Therefore, this Available check does not tell you if a whole line is available. Also, there could be multiple lines. The correct way to read is to have a reading loop always running and simply reading lines without checking. Any line that arrives will be processed that way. No need for timers etc.
The server has the same problems.
Issue (2) might have caused the appearance of lost packets somehow. You need to fix this in any case.
I having a little issue reading data from Nave32 Flight Controller, I'm able to send data to the card using the SerialDevice class but when the LoadAsync Method is call and there is no more data to read the app hung and does not move forward, there is not exception during the execution of the process. I look at the app state and there is a bunch a task block and I'm not sure why. See image below
UPDATE
Firmware source code is here
here is my example code
namespace Apps.Receiver
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.dataRecived.Text = DateTime.Now.ToString();
}
private async Task readAsync(SerialDevice serialPort)
{
string data = string.Empty;
using (var dataReaderObject = new DataReader(serialPort.InputStream))
{
try
{
dataReaderObject.InputStreamOptions = InputStreamOptions.None;
var hasData = true;
while (hasData)
{
var bytesRead = await dataReaderObject.LoadAsync(serialPort.DataBits);
if (bytesRead > 0)
data += dataReaderObject.ReadString(bytesRead);
else
hasData = false;
}
}
catch (Exception ex)
{
status.Text = "reading data fail: " + ex.Message;
closeDevice(serialPort);
}
}
dataRecived.Text = data;
}
private async void sendData_Click(object sender, RoutedEventArgs e)
{
var serialPort = await getSerialDevice("COM3");
if (dataToSend.Text.Length != 0)
{
using (var dataWriteObject = new DataWriter(serialPort.OutputStream))
{
try
{
if (dataToSend.Text.Equals("#", StringComparison.CurrentCultureIgnoreCase))
dataWriteObject.WriteString(dataToSend.Text);
else
dataWriteObject.WriteString(dataToSend.Text + "\n");
var bytesWritten = await dataWriteObject.StoreAsync();
if (bytesWritten > 0)
{
status.Text = dataToSend.Text + ", ";
status.Text += "bytes written successfully!";
}
await readAsync(serialPort);
}
catch (Exception ex)
{
status.Text = "writing data fail: " + ex.Message;
}
}
closeDevice(serialPort);
}
else
{
status.Text = "Enter the text you want to write and then click on 'WRITE'";
}
}
private void closeDevice(SerialDevice device)
{
device.Dispose();
device = null;
}
private async Task<SerialDevice> getSerialDevice(string portName)
{
var aqs = SerialDevice.GetDeviceSelector("COM3");
var devices = await DeviceInformation.FindAllAsync(aqs);
if (devices.Count == 0)
throw new Exception("Unablet to connect to device");
var serialPort = await SerialDevice.FromIdAsync(devices[0].Id);
if (serialPort == null)
throw new Exception("Unablet to Open to port " + portName);
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
return serialPort;
}
}
}
See this example, try if it helps doing it like this:
await reader.LoadAsync(8192);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(8192);
}