好的,所以我有一个程序,通过比较某个字符串与我用作参考的“temp”字符串不同,每当有人跟踪该频道时,都会检查一个twitch url。但是,不是每次字符串不同时只输出一条消息,它就会陷入输出最新关注者的循环中,然后再输出第二个最新关注者,然后是最新的关注者等等。
我错过了什么?另外,有没有更好的方法来检查某个字符串是否更新?
private void DonationListen()
{
try
{
followers = this.donationClient.DownloadString("https://api.twitch.tv/kraken/channels/" + channel.Trim() + "/follows");
donationTimer.Interval = 10000;
donationTimer.Elapsed += new ElapsedEventHandler(CheckUpdates);
donationTimer.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void CheckUpdates(object source, ElapsedEventArgs e)
{
donationTimer.Stop();
int startIndex = followers.IndexOf("display_name\":") + 15;
int endIndex = followers.IndexOf(",\"logo", startIndex);
prevFollower = followers.Substring(startIndex, (endIndex - 1) - startIndex);
if (firstRun == true)
{
temp = prevFollower;
}
else if (prevFollower != temp)
{
//New follower detected
temp = prevFollower;
if (updateFollower != null)
{
updateFollower(prevFollower);
}
}
else
{
//Follower is the same as before
}
firstRun = false;
DonationListen();
}
我认为它可能与downloadstring试图从url获取一个新字符串但由于它当前正在更新而失败,因此CheckUpdates没有正确的信息或其他东西?
答案 0 :(得分:1)
如果没有一个好的代码示例,很难确定问题是什么。因此,我们将继续检查您向我们展示的代码。
基于此,在我看来,好像你的"循环"是由多次订阅同一事件引起的。
在DonationListen()
方法中,您有以下声明:
donationTimer.Elapsed += new ElapsedEventHandler(CheckUpdates);
在CheckUpdates()
方法(即您订阅的处理程序)中,您有此语句(作为最后一条语句):
DonationListen();
换句话说,每次引发计时器的Elapsed
事件时,都会向事件添加另一个事件处理程序实例。对于您添加的每个处理程序,将调用CheckUpdates()
方法。
同样,如果没有一个好的代码示例,很难确定最佳解决方案是什么。但是考虑到这里的代码,我觉得你可以从CheckUpdates()
方法中删除最后一个语句,因为DonationListen()
方法似乎没有做任何需要再做的事情。