c# - C# 中的 WebRequest/WebResponse 阻塞

标签 c# .net tcp

我正在尝试从 C# 本地触发信号。目标是向 localhost/serv?stream=SOME_STREAM 发出请求。我不关心从服务器获得响应,我只需要让服务器接收请求。现在我正在使用以下代码,但我并不真正关心使用这些对象——任何解决方案都可以:

    private void updateStreams(string streamname)
    {
        WebRequest myWebRequest = WebRequest.Create(new Uri("http://localhost/serv?stream=" + streamname));
        WebResponse myWebResponse = myWebRequest.GetResponse();
        myWebResponse.Close();
    }

我尝试了一些调试,阻塞调用似乎是 myWebRequest.GetResponse(),但这一行很关键,因为没有它就不会发出请求。我还尝试了以下代码,它在同一点阻塞:

        var myWebRequest = (System.Net.HttpWebRequest)WebRequest.Create(new Uri("http://localhost/serv?stream=" + sesh.session_name));
        using (var myWebResponse = (System.Net.HttpWebResponse)myWebRequest.GetResponse())
        {
            var responseStream = myWebResponse.GetResponseStream();
            responseStream.ReadTimeout = 2; 
            responseStream.Close();
            responseStream.Dispose();
            myWebResponse.Close();
        }

最佳答案

您可以这样使用 WebClient.DownloadStringAsync():

WebClient wc = new WebClient();
wc.DownloadStringCompleted += new  DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("http://localhost/serv?stream=" + streamname));

这将触发请求并在请求完成时调用 wc_DownloadStringCompleted 方法而不阻塞主线程。

关于c# - C# 中的 WebRequest/WebResponse 阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272765/

相关文章:

sockets - 用于身份验证的 chrome 应用程序客户端证书

sockets - redis 服务器套接字在哪里创建?

c# - 在 C# 的内部类中实现内部接口(interface)

c# - 在Windows Phone上同时播放声音

.net - 在 sql 查询中传递整数列表,最佳实践

c# - 使用 C# .Net 访问 SQL Server 数据库的最佳方式

c# - 如何在 ASP.net Core 2 中创建动态 API

c# - ServiceStack - 如何在一项服务中托管多个版本端点?

c# - 复制/反射。发射静态数组

python - 为什么 %en0 后缀无法连接 Python 中的链接本地 IPv6 TCP 套接字?