質問

I want to create an async method that awaits until someone will try to connect something that will look like

await (listener.Pending() == true);

of course, that won't work. How can I do that?

役に立ちましたか?

解決

If you can use async/await then potentially you are using .NET 4.5. If so you can use the AcceptSocketAsync or AcceptTcpClientAsync methods on TcpListener? For example:

await listener.AcceptSocketAsync();

The Pending method does the same checks as these two methods but just returns immediately with a true/false. The two Accept...Async are designed to block until Pending would otherwise return true and then hand you your Socket or TcpClient respectively.

Background

From the Pending documentation:

This non-blocking method determines if there are any pending connection requests. Because the AcceptSocket and AcceptTcpClient methods block execution until the Start method has queued an incoming connection request, the Pending method can be used to determine if connections are available before attempting to accept them.

The Accept...Async methods do the same as the Accept... versions, but you can await them.

他のヒント

You can create a Task from Begin\EndAccept:

var listener = new TcpListener(...);
Task<Socket> acceptTask = Task.Factory.FromAsync<Socket>(listener.BeginAcceptSocket, listener.EndAcceptSocket, null);

var socket = await acceptTask;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top