c# Main thread blocked while connecting to IZKEM Connect_Net blocks UI

272 Views Asked by At

I'm using zkemkeeper SDK to handle Attendance Machine and it is working fine but when I connect, it hangs form UI, so I started using Async Task to avoid this issue but it didn't work and here is my code:

public async Task<bool> Connect()
{
    await Task.Delay(5000);
    await Task.Run(() => ZkemClientObj.Connect_Net(ip, port));
}

in task delay UI was not blocked but when I start Connect_Net it blocks UI. I tried a lot of things and it works fine but only with this snippet.

Update

This is connection button event method:

CZKEM ZkemClientObj = new CZKEM();

private async void MachineConnectionAction(object sender, EventArgs e)
{
    var isConnected = await Connect();

    if (isConnected) 
    {
        UpdateConnectionStatus();
    } 
    else 
    {
        ShowErrorMessage();
    }

}

public async Task<bool> Connect()
{
     string ip = MachineIPAddress.Text.Trim();
     int port = int.Parse(MachinePort.Text.Trim());

     return await Task.Run(() => ZkemClientObj.Connect_Net(ip, port));
}

1

There are 1 best solutions below

3
On

Try this https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskfactory.startnew?view=netframework-4.8

 public async Task Connect()
   {
        await Task.Delay(5000);
        Task.Factory.StartNew(() => ZkemClientObj.Connect_Net(ip, port));
   }