Graeme (Solution 1) is correct that you should
avoid async void
[
^] wherever possible. Unfortunately, that doesn't address the actual problem.
Your two
WriteMultipleCoilsAsync
methods return
Task
, not
Task<T>
. That means there is no result returned from the
Task
. You can
await
it to know when it has completed, but there is nothing to store in your
response
variable.
Assuming your
PerformWriteRequestAsync<WriteMultipleCoilsResponse>
method returns a
Task<WriteMultipleCoilsResponse>
, you simply need to update both overloads of the
WriteMultipleCoilsAsync
method to return the same:
public Task<WriteMultipleCoilsResponse> WriteMultipleCoilsAsync(ushort startAddress, bool[] data)
{
return WriteMultipleCoilsAsync(0, startAddress, data);
}
public Task<WriteMultipleCoilsResponse> WriteMultipleCoilsAsync(byte slaveAddress, ushort startAddress, bool[] data)
{
ValidateData("data", data, 1968);
WriteMultipleCoilsRequest request = new WriteMultipleCoilsRequest(slaveAddress, startAddress, new DiscreteCollection(data));
return PerformWriteRequestAsync<WriteMultipleCoilsResponse>(request);
}
To avoid the
async void
, you will want to move the code that calls this into a separate
Task
-returning method:
private async Task WriteMultipleCoilsAsync()
{
string discretes = "true,false,true";
bool[] diarray = Array.ConvertAll(discretes.Split(','), bool.Parse);
var response = await master.WriteMultipleCoilsAsync(0, diarray);
}
You can then "fire and forget" this task-returning
async
method from the event handler, using a "discard" to avoid the compiler warning:
private void btnWriteMultipleCoils_Click(object? sender, EventArgs e)
{
_ = WriteMultipleCoilsAsync();
}