[英]Compare Strings in C#
好的,我尝试每15秒比较两个字符串,然后更新一个信息框。
到目前为止,这是我从网上获取文本文档并将其存储为字符串的代码:
public String GetData(String url)
{
WebRequest request = WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
String data = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return data;
}
这就是我尝试比较字符串的方法。
public void CompareStrings()
{
int x;
x = 1;
String data = GetData("http://xcastradio.com/stats/nowplaying.txt");
string savedData = data;
while (x > 0 && x < 100000001)
{
x++;
}
String data1 = GetData("http://xcastradio.com/stats/nowplaying.txt");
NowPlayingInfo1.Text = data;
NowPlaying np = new NowPlaying();
if (data1 != savedData)
{
NowPlayingInfo1.Text = data1;
np.Show(this);
}
}
我的意思不是嘴,但目的是:
while (x > 0 && x < 100000001)
{
x++;
}
如果要暂停,为什么不只是Thread.Sleep(TimeSpan.FromSeconds(1))? 您的代码示例没有太大意义。
String.Compare(string1, string2 ......)
给您更多选择。
请参考MSDN上的String.Compare方法
我认为您的CompareStrings()方法应如下所示:
private bool _Comparing = false;
private string _URL = "http://xcastradio.com/stats/nowplaying.txt";
private string _data = "";
public void CompareStrings()
{
Timer timer = new Timer();
timer.Interval = 1000;
timer.Tick += timer_Tick;
_data = GetData(_URL);
_Comparing = true;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
if (_Comparing)
{
string newdata = GetData(_URL);
if (newdata != _data)
{
NowPlaying np = new NowPlaying();
NowPlayingInfo1.Text = newdata;
_data = newdata;
np.Show(this);
}
}
else
{
Timer timer = (Timer)sender;
timer.Stop();
}
}
此代码使用Timer
每秒检查一次URL。 每当此文本文件的内容更改时,此代码都会弹出一个新的NowPlaying
窗口(这是我认为您要尝试的操作),并将继续执行此操作,直到将_Comparing
设置为false
为止。
您可能还希望轮询URL的频率小于每秒一次,在这种情况下,您可以将timer.Interval
设置为10000(10秒)之类的值。
public void CompareStrings()
{
String data = GetData("http://xcastradio.com/stats/nowplaying.txt");
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(15));
String data1 = GetData("http://xcastradio.com/stats/nowplaying.txt");
NowPlayingInfo1.Text = data;
NowPlaying np = new NowPlaying();
if (String.Compare(data, data1) != 0)
{
NowPlayingInfo1.Text = data1;
np.Show(this);
}
}
用于检查正在播放的歌曲的线程应与主应用程序线程分开,因为它处于休眠状态,并且您希望(我认为)您的应用程序即使在两次检查之间也要保持响应。
编辑:比较现在应该正确工作(未经测试)。
我建议您改用以下内容:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.