c#.net中超时异常 [英] Time out exception in c#.net

查看:83
本文介绍了c#.net中超时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i在下面提到超时异常,行提到// --------------------- //

Hi,
i getting timeout exception in below, line mentioned //---------------------//

Stream dataStream = request.GetRequestStream();



// ------------ --------------------------------- //善意解决我的问题,,,,








//---------------------------------------------// kindly solve my problem,,,,



// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://mindapp-pulpy.rhcloud.com/AuthXmlPulpy");
//request.Proxy = new System.Net.WebProxy(ProxyString, true);
// Set the Method property of the request to POST.
request.Method = "POST";
request.Headers["X-Parse-Application-Id"] = "MPAPP_028";
//request.Headers["X-Parse-REST-API-Key"] = "my_secret_rest_api_key";
// Create POST data and convert it to a byte array.
string postData = "piano";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/xml";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
//--------------------------------------------//
Stream dataStream = request.GetRequestStream();
//---------------------------------------------//
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription, "POST Test");
// Get the stream containing content returned by the server.
using (XmlReader reader = XmlReader.Create(dataStream))
{
    while (reader.Read())
    {
        if (reader.ToString().Contains(""))
        {
            switch (reader.Name.ToString())
            {
                case "a":
                    MessageBox.Show(reader.ReadString());
                    break;
                case "b":
                    MessageBox.Show(reader.ReadString());
                    break;
            }
        }
     }
 }

推荐答案

Hello Chellapandi160 ,



尝试调用GetRequestStream()时会出现多种原因超时异常;



一根据我的经验,请求失败的最常见原因是因为API服务没有返回任何内容或请求方发生某种错误。



大多数情况下,只需对代码进行一些更改即可清除这些错误。



Hello Chellapandi160,

Timeout exceptions can happen for many reasons when trying to call a GetRequestStream();

One of the most common reasons why the request fails, from my experience, is because the API service doesn't return anything or some sort of error happens on the request side.

Most times just a little change to your code can clean up these errors.

using (var dataStream = request.GetRequestStream())
{
    if (dataStream == null)
    {
        MessageBox.Show("DataStream is null");
        return;
    }
    //Do everything else down here.
};





此代码的工作原因是因为在尝试连接到API服务时,可能会有防火墙或代理阻止它。当学生使用他们的学校网络进行连接时,我看到了很多。流将继续尝试获取信息,因为阻塞而无法在哪里创建超时异常。



或者你可以这样做:





The reason why this code works is because when trying to connect to the API service there could be a firewall or proxy blocking it. I see this a lot when students are using their schools network to do the connection. The stream will keep trying to get information, getting no where because of the block thus creating a timeout exception.

Or you can do:

var request = (HttpWebRequest)WebRequest.Create("https://mindapp-pulpy.rhcloud.com/AuthXmlPulpy");





(HttpWebRequest)WebRequest确保GetRequestStream永远不能为null。



但是,通过测试代码,我还发现您尝试读取的流不支持只读写。现在我对Mind Pulpy并不熟悉,但这也可能是你的超时问题。



我刚刚点击按钮测试了它,所以这里是编辑过的代码。试试看它是否适合你。





(HttpWebRequest)WebRequest makes sure that the GetRequestStream can never be null.

However from testing your code I have also found out that the stream that you are trying to read from does not support reading only writing. Now I am not familiar with Mind Pulpy, but that could be apart of your timeout problem too.

I just tested it out on a button click so here is the edited code. Give it a shot to see if it works for you.

{
    var request = (HttpWebRequest)WebRequest.Create("https://mindapp-pulpy.rhcloud.com/AuthXmlPulpy");
    request.Method = "POST";
    request.Headers["X-Parse-Application-Id"] = "MPAPP_028";
    request.ContentType = "application/xml";
    var byteArray = Encoding.UTF8.GetBytes("piano");
    request.ContentLength = byteArray.Length;
    using (var dataStream = request.GetRequestStream())
    {
        if (dataStream.CanWrite)
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
        }
        else
        {
            MessageBox.Show("DataStream can not write.");
        }
        var response = request.GetResponse();
        MessageBox.Show(((HttpWebResponse) response).StatusDescription, "POST Test");
        if (dataStream.CanRead)
        {
            using (var reader = XmlReader.Create(dataStream))
            {
                while (reader.Read())
                {
                    if (!reader.ToString().Contains("")) continue;
                    switch (reader.Name)
                    {
                        case "a":
                            MessageBox.Show(reader.ReadString());
                            break;
                        case "b":
                            MessageBox.Show(reader.ReadString());
                            break;
                    }
                }
            }
        }
        else
        {
            MessageBox.Show("Datastream can not read.");
        }
    }
}





无论如何,这应解决你的超时异常。现在,他们总是有可能阻止或列入您的API,这可能会使请求失败。



希望这会有所帮助,

CodeFate



PS。请尽量不要集成Timeout.Infinite或KeepAlive这一切都是允许时间。如今,互联网足够快,可以在短时间内获得请求。如果您使用非常慢的互联网或连接不稳定,这是一个很好的选择,但如果请求有错误(是的,您猜对了)无限的时间,它会冻结您的应用程序。



Anyway this should solve your timeout exception. Now there is always a chance that they have blocked or blacklisted your API and this could fail the request.

Hopefully this helps,
CodeFate

PS. Please try not to integrate a Timeout.Infinite or KeepAlive all this does is allow time. Internet is fast enough nowadays to get the request within moments. It's a great option if you are using a very slow internet or the connection is unstable, but it will freeze your application if the request has errors for (yep you guessed it) a Infinite amount of time.


首先:他们可能已阻止或将您列入黑名单。也许你的开发被认为是可疑行为。

无论如何,请尝试 request.Timeout = Timeout.Infinite; 请求。 KeepAlive = true;
first of all: they may have blocked or blacklisted you. maybe your development was recognized as suspicious behavior.
anyway, try request.Timeout = Timeout.Infinite; and request.KeepAlive = true;


这篇关于c#.net中超时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆