我在c#中使用程序集引用dll來控制一些網絡設備!當我嘗試連接網絡設備時,用戶界面停止連接建立! 爲了解決這個問題,我沒有使用線程/異步的await(.NET Framework 4.0中),但問題仍然沒有解決......用戶界面停止使用某些方法的程序集引用dll
這裏是我的代碼(使用線程):
public void startListening(string IP, string Port)
{
if (!ThreadBusy)
{
if (IP.Trim() == "" || Port.Trim() == "") return;
Conn = new Thread(() => start(IP, Port));
Conn.Start();
ThreadBusy = true;
}
}
private void start(string IP, string Port)
{
if (!bIsConnected && !isListening)
{
//This Line Will Make UI Freez...
bIsConnected = axCZKEM1.Connect_Net(IP, Convert.ToInt32(Port));
if (bIsConnected == true)
{
iMachineNumber = 1;
deviceType = axCZKEM1.IsTFTMachine(iMachineNumber) ? 1 : 2;
this.IP = IP;
this.isListening = true;
if (axCZKEM1.RegEvent(iMachineNumber, 65535))
{
switch (deviceType)
{
case 1:
EnableTFTEvents();
break;
case 2:
EnableBWEvents();
break;
case 3:
//---
break;
}
ConnectionFailedArgs args = new ConnectionFailedArgs();
args.IP = IP;
OnConnectionSucceed(args);
}
}
else
{
ConnectionFailedArgs args = new ConnectionFailedArgs();
args.IP = IP;
OnConnectionFailed(args);
}
ThreadBusy = false;
}
}
我想知道使用此線程時在UI上發生了什麼?
我將VS從2010升級到2012(.Net Framework 4.5),但問題仍未解決!
這裏是我的代碼(使用異步的await):
public async void startListening(string IP, string Port)
{
if (!ThreadBusy)
{
if (IP.Trim() == "" || Port.Trim() == "") return;
//Conn = new Thread(() => start(IP, Port));
//Conn.Start();
ThreadBusy = true;
await Task.Run(() => start(IP,Port));
}
}
private async Task start(string IP, string Port)
{
if (!bIsConnected && !isListening)
{
//This Line Will Make UI Freez...
bIsConnected = axCZKEM1.Connect_Net(IP, Convert.ToInt32(Port));
if (bIsConnected == true)
{
deviceType = axCZKEM1.IsTFTMachine(iMachineNumber) ? 1 : 2;
this.IP = IP;
this.isListening = true;
if (axCZKEM1.RegEvent(iMachineNumber, 65535))
switch (deviceType)
{
case 1:
EnableTFTEvents();
break;
case 2:
EnableBWEvents();
break;
case 3:
//---
break;
}
ConnectionFailedArgs args = new ConnectionFailedArgs();
args.IP = IP;
OnConnectionSucceed(args);
}
}
else
{
ConnectionFailedArgs args = new ConnectionFailedArgs();
args.IP = IP;
OnConnectionFailed(args);
}
ThreadBusy = false;
}
}
'Aync/await'與'Threads'不一樣,它是在.NET 4.5 –
中介紹的我知道!但是我下載了[「Microsoft Visual Studio Async CTP」](http://download.microsoft.com/download/7/B/5/7B59A157-A908-4F6E-85D7-EB93E3A4DC00/Async-CTP-v3.exe)包分開... –
如果你想知道在UI線程上發生了什麼,那麼你需要使用調試器。使用Debug + Windows +線程來選擇它。如果你看到它陷入循環,等待ThreadBusy,那麼你一定會發現問題。 –