即使在阅读完文档后,我也不明白我在C#中使用异步操作可以获得哪些信息。我有一个TpcClient,我希望它尝试连接x次。到目前为止:
public async Task SocketConnect() {
tcpClient = new TcpClient();
for(int i = 0; i < maxConnectionAttempts; i++) {
OpenSocket();
await Task.Delay(5000);
}
}
private void OpenSocket() {
try {
tcpClient.BeginConnect(host, port, ConnectCallback, tcpClient);
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private void ConnectCallback(IAsyncResult result) {
try {
tcpClient.EndConnect(result);
// Connected
if (tcpClient.Connected) {
Console.WriteLine("connected");
if (OnClientEvent != null)
OnClientEvent(this, new ClientEventArgs(Action.Connect));
stream = tcpClient.GetStream();
BeginReadAsync();
}
// Not connected
else {
Console.WriteLine("not connected");
Console.WriteLine("Retrying");
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
我错过了SocketConnect()
方法中的逻辑。我不确定我能如何await
OpenSocket()
,因为它的结果会被转移到不同的回调中。我可以从OpenSocket()
返回什么,以便我知道它已连接?
答案 0 :(得分:1)
你进入了什么样的混乱局面。
你混合了两种不同类型的异步...... Task Asynchronous Pattern和(相当混乱)Asynchronous Programming Model。我建议你放弃APM(这是旧的和sh * t)并坚持使用TAP,因为它允许你编写异步代码 而不用 回调,这样你就会更简单了,可读代码。
如果我理解正确,你要做的就是:
public async Task SocketConnect() {
var tcpClient = new TcpClient();
for(var retries = 0; retries < 5; retries++)
{
try
{
await tcpClient.ConnectAsync(host, port);
}
catch(Exception ex)
{
//handle errors
continue;
}
if(tcpClient.Connected) break;
}
if(tcpClient.Connected)
{
//yay
}
}