关闭流时的奇怪行为 [英] Strange behavior when closing stream

查看:76
本文介绍了关闭流时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我正在使用StreamReader
我在下面的代码中使用的
对象遇到一些非常奇怪的行为。总结一下,我正在从网站下载一个文件并将其保存到磁盘以进行进一步的解析。我知道,我可以使用WebClient,它会更容易,但我不会因为它而具有我想要的灵活性。


除非用户

取消后台操作,否则此代码似乎完全按照我想要的方式工作。在这种情况下,当我在StreamReader对象上调用

Close()时,该方法就结束了。在调用Close()之后,没有什么

执行;这导致一些不好的一面

效果。如果我注释掉Reader.Close()行,它就能完美运行。

但是,我担心不关闭那个流会导致我某种方式出现问题。\\ br
问题。 />

我发现它不是在我打电话时关闭,而是当我尝试使用
来读取更多数据或其他任何与流。属性

可以检查,但方法会导致相同的行为。


如果未单击取消按钮,代码将正确执行。


欢迎任何想法或建议。


统计:XP,VS2005,SQLServer 2005


谢谢,


John


ps我是.Net2的新手和一般的线程。 :)

private void backgroundWorker_DoWork(object sender,DoWorkEventArgs e)

{

try

{

MyPostVars vasr = e.Argument as MyPostVars;

ASCIIEncoding encoding = new ASCIIEncoding();

byte [] data = encoding.GetBytes(vars.ToPostString ());


HttpWebRequest request =

(HttpWebRequest)WebRequest.Create(" https://www.someCrazyWebsite/Download.do");

request.ContentLength = data.Length;

requ est.ContentType =" application / x-www-form-urlencoded";

request.Method =" POST";


流requestStream = request.GetRequestStream();

requestStream.Write(data,0,data.Length) ;

requestStream.Close();


HttpWebResponse response =

(HttpWebResponse)request.GetResponse();


StreamReader reader = new

StreamReader(response.GetResponseStream());


System.IO .FileInfo file = new

System.IO.FileInfo(" outputfile.txt");

if(file.Exists)

{

file.Delete();

}


StreamWriter writer = new StreamWriter(file.FullName);

writer.AutoFlush = true;


int count = 0;

int read = 0;

int size = 65536;

char [] buffer = new char [size];


while(!backgroundWorker.CancellationPending&&

!reader.EndOfStream)

{

count = reader.Read(buffer,0,size);

read + = count;

writer.Write(buffer,0,count);

backgroundWorker.ReportProgress(0,read);

}


reader.Close(); < --------------------问题!!!!!!!!

writer.Close();


if(backgroundWorker.CancellationPending)

{

e.Cancel = true;

}

}

catch(exception ex)

{

MessageBox.Show(ex.Message);

}

终于

{

}


}

Hello all,

I''m experiencing some, imo, strange behavior with the StreamReader
object I am using in the code below. Summary is that I am downloading
a file from a website and saving it to disk for further parsing. I
know, I could use the WebClient and it would be easier, but I don''t
have the flexibility I want with it.

This code appears to work exactly the way I want unless the user
cancels the the background operation. In that case, when I call
Close() on the StreamReader object, the method just ends. Nothing
after the call to Close() get executed; which causes some bad side
effect. If I comment out the Reader.Close() line, it work perfectly.
However, I am worried that not closing that stream will cause me
problems somehow.

I have found that it isn''t just when I call close, it''s when I attempt
to read more data or anything else dealing with the stream. Properties
are ok to check, but methods cause the same behavior.

The code executes correctly if the cancel button is not clicked.

Any ideas or suggestions welcome.

Stats: XP, VS2005, SQLServer 2005

Thanks,

John

p.s. I''m new to .Net2 and threading in general. :)
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
MyPostVars vasr = e.Argument as MyPostVars;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(vars.ToPostString());

HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("https://www.someCrazyWebsite/Download.do");
request.ContentLength = data.Length;
requ est.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";

Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

HttpWebResponse response =
(HttpWebResponse)request.GetResponse();

StreamReader reader = new
StreamReader(response.GetResponseStream());

System.IO.FileInfo file = new
System.IO.FileInfo("outputfile.txt");
if (file.Exists)
{
file.Delete();
}

StreamWriter writer = new StreamWriter(file.FullName);
writer.AutoFlush = true;

int count = 0;
int read = 0;
int size = 65536;
char[] buffer = new char[size];

while (!backgroundWorker.CancellationPending &&
!reader.EndOfStream)
{
count = reader.Read(buffer, 0, size);
read += count;
writer.Write(buffer, 0, count);
backgroundWorker.ReportProgress(0, read);
}

reader.Close(); <-------------------- Problem!!!!!!!!
writer.Close();

if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}

}

推荐答案

John,


我不太了解你的游戏细节 - 他们倾向于

是idiosynchratic - 但尝试使用(StreamReader reader = new

StreamReader(response.GetResponseStream()))

{

...

}


阻止读者。您应该可以避免拨打

关闭(),这可能会解决您的问题。


您关闭后期望发生什么? )无论如何要打电话?

看起来可能存在一些线程问题。你在后台线程的线程边界周围有一个try / catch

块吗?

Stephan



John Kraft写道:
John,

I don''t know too much about the details of your stream -- they tend to
be idiosynchratic -- but try a

using (StreamReader reader = new
StreamReader(response.GetResponseStream()))
{
...
}

block around your reader. You should be able to avoid the call to
Close(), which may solve your problem.

What do you expect to be happening after your Close() call anyway?
Looks like there may be some threading issues. Do you have a try/catch
block around the thread boundary of the background thread?
Stephan


John Kraft wrote:

大家好,


我正在使用StreamReader遇到一些非常奇怪的行为

我在下面的代码中使用的对象。总结一下,我正在从网站下载一个文件并将其保存到磁盘以进行进一步的解析。我知道,我可以使用WebClient,它会更容易,但我不会因为它而具有我想要的灵活性。


除非用户

取消后台操作,否则此代码似乎完全按照我想要的方式工作。在这种情况下,当我在StreamReader对象上调用

Close()时,该方法就结束了。在调用Close()之后,没有什么

执行;这导致一些不好的一面

效果。如果我注释掉Reader.Close()行,它就能完美运行。

但是,我担心不关闭那个流会导致我某种方式出现问题。\\ br
问题。 />

我发现它不是在我打电话时关闭,而是当我尝试使用
来读取更多数据或其他任何与流。属性

可以检查,但方法会导致相同的行为。


如果未单击取消按钮,代码将正确执行。


欢迎任何想法或建议。


统计:XP,VS2005,SQLServer 2005


谢谢,


John


ps我是.Net2的新手和一般的线程。 :)


private void backgroundWorker_DoWork(object sender,DoWorkEventArgs e)

{

try

{

MyPostVars vasr = e.Argument as MyPostVars;

ASCIIEncoding encoding = new ASCIIEncoding();

byte [] data = encoding.GetBytes (vars.ToPostString());


HttpWebRequest请求=

(HttpWebRequest)WebRequest.Create(" https://www.someCrazyWebsite/Download。 do);

request.ContentLength = data.Length;

requ est.ContentType =" application / x-www-form-urlencoded";

request.Method =" POST";


流requestStream = request.GetRequestStream();

requestStream.Write(data,0, data.Length);

requestStream.Close();


HttpWebResponse response =

(HttpWebResponse)request.GetResponse() ;


StreamReader reader = new

StreamReader(response.GetResponseStream());


System.IO.FileInfo file = new

系统.IO.FileInfo(" outputfile.txt");

if(file.Exists)

{

file.Delete();

}


StreamWriter writer = new StreamWriter(file.FullName);

writer.AutoFlush = true;


int count = 0;

int read = 0;

int size = 65536;

char [] buffer = new char [size];


while(!backgroundWorker.CancellationPending&&

!reader.EndOfStream)

{

count = reader.Read(buffer,0,size);

read + = count;

writer.Write(buffer, 0,计数);

backgroundWorker.ReportProgress(0,读取);

}


reader.Cl OSE(); < --------------------问题!!!!!!!!

writer.Close();


if(backgroundWorker.CancellationPending)

{

e.Cancel = true;

}

}

catch(exception ex)

{

MessageBox.Show(ex.Message);

}

终于

{

}


}
Hello all,

I''m experiencing some, imo, strange behavior with the StreamReader
object I am using in the code below. Summary is that I am downloading
a file from a website and saving it to disk for further parsing. I
know, I could use the WebClient and it would be easier, but I don''t
have the flexibility I want with it.

This code appears to work exactly the way I want unless the user
cancels the the background operation. In that case, when I call
Close() on the StreamReader object, the method just ends. Nothing
after the call to Close() get executed; which causes some bad side
effect. If I comment out the Reader.Close() line, it work perfectly.
However, I am worried that not closing that stream will cause me
problems somehow.

I have found that it isn''t just when I call close, it''s when I attempt
to read more data or anything else dealing with the stream. Properties
are ok to check, but methods cause the same behavior.

The code executes correctly if the cancel button is not clicked.

Any ideas or suggestions welcome.

Stats: XP, VS2005, SQLServer 2005

Thanks,

John

p.s. I''m new to .Net2 and threading in general. :)
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
MyPostVars vasr = e.Argument as MyPostVars;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(vars.ToPostString());

HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("https://www.someCrazyWebsite/Download.do");
request.ContentLength = data.Length;
requ est.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";

Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

HttpWebResponse response =
(HttpWebResponse)request.GetResponse();

StreamReader reader = new
StreamReader(response.GetResponseStream());

System.IO.FileInfo file = new
System.IO.FileInfo("outputfile.txt");
if (file.Exists)
{
file.Delete();
}

StreamWriter writer = new StreamWriter(file.FullName);
writer.AutoFlush = true;

int count = 0;
int read = 0;
int size = 65536;
char[] buffer = new char[size];

while (!backgroundWorker.CancellationPending &&
!reader.EndOfStream)
{
count = reader.Read(buffer, 0, size);
read += count;
writer.Write(buffer, 0, count);
backgroundWorker.ReportProgress(0, read);
}

reader.Close(); <-------------------- Problem!!!!!!!!
writer.Close();

if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}

}


John Kraft写道:
John Kraft wrote:

我正在使用StreamReader体验一些非常奇怪的行为

我在下面的代码中使用的对象。总结一下,我正在从网站下载一个文件并将其保存到磁盘以进行进一步的解析。我知道,我可以使用WebClient,它会更容易,但我不会因为它而具有我想要的灵活性。


除非用户

取消后台操作,否则此代码似乎完全按照我想要的方式工作。在这种情况下,当我在StreamReader对象上调用

Close()时,该方法就结束了。在调用Close()之后,没有什么

执行;这导致一些不好的一面

效果。
I''m experiencing some, imo, strange behavior with the StreamReader
object I am using in the code below. Summary is that I am downloading
a file from a website and saving it to disk for further parsing. I
know, I could use the WebClient and it would be easier, but I don''t
have the flexibility I want with it.

This code appears to work exactly the way I want unless the user
cancels the the background operation. In that case, when I call
Close() on the StreamReader object, the method just ends. Nothing
after the call to Close() get executed; which causes some bad side
effect.



这听起来像是一个异常被抛出。


1)你应该弄清楚你的一般异常处理机制所以

你可以看到那个例外

2)这个例外情况可能会提供有助于你的信息

理解为什么会发生这种情况。


Jon

That sounds like an exception is being thrown.

1) You should work out your general exception handling mechanisms so
that you get to see that exception
2) The exception is likely to provide information which will help you
understand why it''s happening.

Jon


2006年10月24日08:57:45 -0700,Jon Skeet [ C#MVP]" < sk *** @ pobox.com>

写道:
On 24 Oct 2006 08:57:45 -0700, "Jon Skeet [C# MVP]" <sk***@pobox.com>
wrote:

> John Kraft写道:
>John Kraft wrote:

>我正在使用我在下面的代码中使用的StreamReader
对象遇到一些非常奇怪的行为。总结是我正在从网站下载文件并将其保存到磁盘以进行进一步解析。我知道,我可以使用WebClient,它会更容易,但我不具备我想要的灵活性。

此代码似乎完全正常工作除非用户取消后台操作,否则我想要的方式。在这种情况下,当我在StreamReader对象上调用
Close()时,该方法就结束了。在调用Close()之后没有任何事情被执行;这会导致一些不好的一面效果。
>I''m experiencing some, imo, strange behavior with the StreamReader
object I am using in the code below. Summary is that I am downloading
a file from a website and saving it to disk for further parsing. I
know, I could use the WebClient and it would be easier, but I don''t
have the flexibility I want with it.

This code appears to work exactly the way I want unless the user
cancels the the background operation. In that case, when I call
Close() on the StreamReader object, the method just ends. Nothing
after the call to Close() get executed; which causes some bad side
effect.


这听起来像是一个异常被抛出。

1)你应该弄清楚你的一般异常处理机制,以便你能看到那个例外
2)这个例外很可能提供的信息可以帮助你理解它为什么会发生。

Jon


That sounds like an exception is being thrown.

1) You should work out your general exception handling mechanisms so
that you get to see that exception
2) The exception is likely to provide information which will help you
understand why it''s happening.

Jon



感谢您输入,Jon。

我在DoWork方法的整个内部尝试/捕获,

来自什么我过去几天读到的是你应该做的b $ b。没有例外出现被抛出;也就是说,
永远不会在catch块内停止。好像线程只是停止了存在的b $ b。我还尝试将单个调用包装在try / catch中的Close

方法中(用于故障排除),没有

运气。我不知道还有什么地方可以试试/抓住这样的

例外。


真正爬行的部分我的意思是,只有

我才会尝试在streamreader上行动。如果我注释掉这个电话,那么

功能会正常终止。


Thanks for the input, Jon.
I''ve got a try/catch around the entire inside of the DoWork method,
which from what I''ve read over the past several days is what you''re
supposed to do. No exception "appears" to be thrown; that is, it
never stops inside the catch block. It''s as if the thread just ceases
to exist. I''ve also tried wrapping the individual call to the Close
method inside a try/catch (for troubleshooting purposes) with no
luck. I don''t know where else I could put a try/catch to catch such
an exception.

The part that really "creeps" me out is that it only seems to occur if
I try to act on the streamreader. If I comment out the call, the
function terminates normally.


这篇关于关闭流时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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