当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - BeginGetRequestStream creates thread that doesn't allow application exit when the host unreachable

问题描述:

static void RequestStreamCallback(IAsyncResult res) {

var req = res.AsyncState as System.Net.WebRequest;

try {

var stream = req.EndGetRequestStream(res);

}

catch (Exception e) {

Console.WriteLine(e.Message);

}

}

static void TimeoutCallback(object state, bool timedout) {

if (timedout) {

Console.WriteLine("Timed out");

var wr = state as System.Net.WebRequest;

wr.Abort();

}

}

static void Main(string[] args){

var webRequest = System.Net.WebRequest.Create("http://192.168.20.135:8000");

webRequest.Method = "POST";

webRequest.ContentType = "text/xml";

webRequest.Timeout = 1000;

var asyncRes = webRequest.BeginGetRequestStream(RequestStreamCallback, webRequest);

System.Threading.ThreadPool.RegisterWaitForSingleObject(asyncRes.AsyncWaitHandle, TimeoutCallback, webRequest, 3000, true);

Console.WriteLine("Begin waiting");

while (!asyncRes.IsCompleted) {

System.Threading.Thread.Sleep(200);

}

Console.WriteLine("Process Try exit");

return;

}

After 3 seconds I have some messages. Last of their is "Process Try Exit", than Process waits for something about 20 seconds and finishes. When host in my URL is reachable there is no problem.

I'm using VS2008 with .NET Framework 3.5

分享给朋友:
您可能感兴趣的文章:
随机阅读: