Webリクエストがあり、streamreaderで情報を読み取ります。15秒後にこのストリームリーダーの後で停止したいと思います。読むプロセスに時間がかかることもありますが、うまくいくこともあります。読み取りプロセスに15秒以上かかる場合、どうすれば停止できますか?私はすべてのアイデアを開いています。
1316 次
3 に答える
2
「Web リクエスト」と言うので、ストリーム リーダーは、インスタンスから を呼び出しSystem.IO.Stream
て取得した をラップすると仮定します。HttpWebRequest
httpWebRequest.GetResponse().GetResponseStream()
その場合は、 を参照してくださいHttpWebRequest.ReadWriteTimeout
。
于 2010-08-03T14:56:49.080 に答える
1
System.Threading.Timer を使用して、オン ティック イベントを 15 秒間設定します。それは最もきれいではありませんが、うまくいきます。または多分ストップウォッチ
--ストップウォッチオプション
Stopwatch sw = new Stopwatch();
sw.Start();
while (raeder.Read() && sw.ElapsedMilliseconds < 15000)
{
}
--タイマーオプション
Timer t = new Timer();
t.Interval = 15000;
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
t.Start();
read = true;
while (raeder.Read() && read)
{
}
}
private bool read;
void t_Elapsed(object sender, ElapsedEventArgs e)
{
read = false;
}
于 2010-08-03T14:41:24.363 に答える
0
タスクを別のスレッドで実行し、メイン スレッドから 15 秒以上実行されているかどうかを監視する必要があります。
string result;
Action asyncAction = () =>
{
//do stuff
Thread.Sleep(10000); // some long running operation
result = "I'm finished"; // put the result there
};
// have some var that holds the value
bool done = false;
// invoke the action on another thread, and when done: set done to true
asyncAction.BeginInvoke((res)=>done=true, null);
int msProceeded = 0;
while(!done)
{
Thread.Sleep(100); // do nothing
msProceeded += 100;
if (msProceeded > 5000) break; // when we proceed 5 secs break out of this loop
}
// done holds the status, and result holds the result
if(!done)
{
//aborted
}
else
{
//finished
Console.WriteLine(result); // prints I'm finished, if it's executed fast enough
}
于 2010-08-03T14:43:24.173 に答える