我们在 .NET 4.0 中是否有机会等待响应然后返回响应?
目前我正在这样做,但它不是很好,我不喜欢它:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
byte[] options = new byte[]{1,1,0};
COMManager mgr = new COMManager("COM1");
byte[] result = mgr.GetResponse(options);
}
}
还有我的 COM 管理器类(我必须在单独的类(dll)中进行操作):
public class COMManager
{
SerialPort sp = null;
byte[] result = null;
bool completed = false;
public COMManager(string comport)
{
sp = new SerialPort(comport);
sp.DataReceived +=new SerialDataReceivedEventHandler(sp_DataReceived);
}
public byte[] GetResponse(byte[] option)
{
sp.Write(option, 0, option.Length);
//I don't like the way...
while (!completed) { }
completed = false;
return result;
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
result = new byte[sp.BytesToRead];
sp.Read(result, 0, sp.BytesToRead);
completed = true;
}
}
在 .NET 4.5 中,我们可能有机会使用“await”语句。但是对于当前项目,我们只允许使用 .NET 4.0。有任何想法吗?