Skip to content

Commit 725369d

Browse files
Fix EnforceRateLimit
Not resetting _requestsThisBurst meant that after 30 calls to the Reddit API you would only be able to make one call per minute. I fixed this by resetting _requestsThisBurst to 0 when _burstStart is reset. Not making the method synchronized meant that there existed a race condition where more than 30 requests would be transmitted every 60 seconds. This can be exhibited by printing _requestsThisBurst on every EnforceRateLimit call and making a demo program that calls the API many times in parallel, for example ```var posts = reddit.GetSubreddit("askreddit").Hot.Take(100); Parallel.ForEach(posts, post => { var topCommentAuthor = post.Comments.FirstOrDefault().Author });```
1 parent aad8878 commit 725369d

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

RedditSharp/WebAgent.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Linq;
55
using System.Net;
66
using System.Reflection;
7+
using System.Runtime.CompilerServices;
78
using System.Text;
89
using System.Threading;
910
using System.Web;
@@ -137,6 +138,7 @@ public JToken ExecuteRequest(HttpWebRequest request)
137138

138139
}
139140

141+
[MethodImpl(MethodImplOptions.Synchronized)]
140142
private static void EnforceRateLimit()
141143
{
142144
switch (RateLimit)
@@ -154,6 +156,7 @@ private static void EnforceRateLimit()
154156
while ((DateTime.UtcNow - _burstStart).TotalSeconds < 10)
155157
Thread.Sleep(250);
156158
_burstStart = DateTime.UtcNow;
159+
_requestsThisBurst = 0;
157160
}
158161
_requestsThisBurst++;
159162
break;
@@ -165,6 +168,7 @@ private static void EnforceRateLimit()
165168
while ((DateTime.UtcNow - _burstStart).TotalSeconds < 60)
166169
Thread.Sleep(250);
167170
_burstStart = DateTime.UtcNow;
171+
_requestsThisBurst = 0;
168172
}
169173
_requestsThisBurst++;
170174
break;

0 commit comments

Comments
 (0)