以下代码是正确的,我正在为 UdpClient
做一些设置,然后使用 Observable.Using(()
?
请建议是否有另一种写作方式?
public static IObservable<UdpReceiveResult> UdpStream()
{
return Observable.Defer(() =>
{
UdpClient receiverUDP = new UdpClient();
receiverUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiverUDP.EnableBroadcast = true;
receiverUDP.Client.ExclusiveAddressUse = false;
receiverUDP.Client.Bind(new IPEndPoint(IPAddress.Any, 514));
return Observable.Using(() => receiverUDP,
udpClient => Observable.Defer(() =>
udpClient.ReceiveAsync().ToObservable()).Repeat());
});
}
根据注释中的请求:
public static IObservable<UdpReceiveResult> UdpStream()
{
return Observable.Defer(() =>
{
UdpClient receiverUDP = new UdpClient();
receiverUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiverUDP.EnableBroadcast = true;
receiverUDP.Client.ExclusiveAddressUse = false;
receiverUDP.Client.Bind(new IPEndPoint(IPAddress.Any, 514));
return
Observable
.Using(
() => receiverUDP,
udpClient =>
Observable
.Defer(() =>
Observable
.FromAsync(() => udpClient.ReceiveAsync()))
.Repeat());
});
}
就个人而言,我会这样做:
public static IObservable<UdpReceiveResult> UdpStream()
{
return
Observable
.Using(
() =>
{
UdpClient receiverUDP = new UdpClient();
receiverUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiverUDP.EnableBroadcast = true;
receiverUDP.Client.ExclusiveAddressUse = false;
receiverUDP.Client.Bind(new IPEndPoint(IPAddress.Any, 514));
return receiverUDP;
},
udpClient =>
Observable
.Defer(() =>
Observable
.FromAsync(() => udpClient.ReceiveAsync()))
.Repeat());
}