Reputation: 83
I am trying to set up a system preventing my application from working if the USB cable of the device is disconnected. For that, if the person activates a function, instead of crashing the application, I bring the user to a loading screen while waiting for the cable to be reconnected.
I have already done a lot of research without actually finding a solution to correct this error and allow me to make it work as I wish. Here is my code:
public async Task WaitingPort()
{
var controllerPort = await this.ShowProgressAsync("Seeking device", " "); //Warning starts here
controllerPort.SetIndeterminate();
await Task.Run(() =>
{
while (port is null)
{
port = CheckPort();
controllerPort.SetMessage("please plub USB");
}
});
await controllerPort.CloseAsync();
}
private SerialPort CheckPort()
{
string[] listPort = SerialPort.GetPortNames();
foreach(string namePort in listPort)
{
SerialPort port = new SerialPort(namePort, 9600);
if (!port.IsOpen)
{
try
{
port.Open();
port.ReadTimeout = 1500;
string data = port.Readline();
if (data.Substring(0, 1) == "A")
{
port.ReadTimeout = 200;
port.Write("777"); // to make it stop sending "A"
return port;
}
else
{
port.Close();
}
}
catch (Exception e1)
{
port.Close();
}
}
}
return null;
}
public MainWindow()
{
WaitingPort(); //WARNING CS4014
...
}
private async void Button_ClickOpen(object sender, RoutedEventArgs e)
{
var controllerPort = await this.ShowProgressAsync("Please wait", " ");
controllerPort.SetIndeterminate();
await Task.Run(() =>
{
try
{
blabla
}
catch (Exception)
{
WaitingPort(); //WARNING CS4014
}
}
}
I've already tried multiple solutions... :
Turning my Void into a Task
_ = WaitingPort(); // hide the error without solving it
WaitingPort().Wait(); // same case here, hiding but not solving
await MyAsyncMethod().ConfigureAwait(false); // same case here, hiding but not solving
Currently, the WaitingPort method only works at startup, otherwise it issues a warning.
I AM NOT TRYING TO HIDE, IGNORE, SUPRESS or whatever THE WARNING like every solutions on stack, but to resolve it, to make it work. Have you guys any idea ?
I really would like my ShowProgressAsync to work properly when called by another methods which are not async
I am not yet very experienced in C#, maybe I'm missing some fundamentals?
Upvotes: 0
Views: 1503
Reputation: 3446
I would use some code like this to solve both problems:
public MainWindow()
{
this.Initialization = this.WaitingPort();
...
}
public Task Initialization { get; }
private async void Button_ClickOpen(object sender, RoutedEventArgs e)
{
await this.Initialization; // Do this in every public method and non-public if they're called out of an 'event'
var controllerPort = await this.ShowProgressAsync("Please wait", " ");
controllerPort.SetIndeterminate();
await Task.Run(async () =>
{
try
{
blabla
}
catch (Exception)
{
await WaitingPort();
}
}
}
This is the way that Stephen Cleary propagates.
Upvotes: 1