似乎System.Timers.Timer
实例通过某种机制保持活跃,但System.Threading.Timer
实例却没有.
示例程序,具有定期System.Threading.Timer
和自动重置功能System.Timers.Timer
:
class Program
{
static void Main(string[] args)
{
var timer1 = new System.Threading.Timer(
_ => Console.WriteLine("Stayin alive (1)..."),
null,
0,
400);
var timer2 = new System.Timers.Timer
{
Interval = 400,
AutoReset = true
};
timer2.Elapsed += (_, __) => Console.WriteLine("Stayin alive (2)...");
timer2.Enabled = true;
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Invoking GC.Collect...");
GC.Collect();
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个程序(.NET 4.0 Client,Release,在调试器之外)时,只有System.Threading.Timer
GC是:
Stayin alive (1)...
Stayin alive (1)...
Stayin alive (2)...
Stayin alive (1)...
Stayin …
Run Code Online (Sandbox Code Playgroud) 我在System.Net.Http中使用HTTPClient来对API发出请求.API限制为每秒10个请求.
我的代码大致是这样的:
List<Task> tasks = new List<Task>();
items..Select(i => tasks.Add(ProcessItem(i));
try
{
await Task.WhenAll(taskList.ToArray());
}
catch (Exception ex)
{
}
Run Code Online (Sandbox Code Playgroud)
ProcessItem方法做了一些事情,但总是使用以下方法调用API :
await SendRequestAsync(..blah)
. 看起来像:
private async Task<Response> SendRequestAsync(HttpRequestMessage request, CancellationToken token)
{
token.ThrowIfCancellationRequested();
var response = await HttpClient
.SendAsync(request: request, cancellationToken: token).ConfigureAwait(continueOnCapturedContext: false);
token.ThrowIfCancellationRequested();
return await Response.BuildResponse(response);
}
Run Code Online (Sandbox Code Playgroud)
最初代码工作正常,但是当我开始使用Task.WhenAll时,我开始从API获得"超出速率限制"消息.如何限制请求的速率?
值得注意的是,ProcessItem可以根据项目进行1-4次API调用.
在C#中,我正在调用一个公共API,其API限制为每秒10次调用.API有多种方法,不同的用户可以一次调用不同的方法,因此可能会出现"速率限制达到"异常.
我有以下类结构:
public class MyServiceManager
{
public int Method1()
{
}
public void Method2()
{
}
public string Method3()
{
}
}
Run Code Online (Sandbox Code Playgroud)
多个用户可以一次调用不同的方法,如何维护静态调用队列或任务,以便我可以监视所有请求并在一秒钟内只接受10个请求
我想在.net(C#或VB)中实现一个好的油门算法,但我无法弄清楚我怎么能这样做.
案例是我的asp.net网站应该将请求发布到另一个网站以获取结果.最多应发送每分钟300个请求.
如果请求超过300限制,则另一方Api不返回任何内容(这是我不想用作检查代码的内容).
PS我见过其他语言的解决方案而不是.net但我是新手,请善待并保持你的答案就像123一样简单.
谢谢
我认同.但是看看asp.net中的内置类:
public sealed class HttpPostedFile
{
public Stream InputStream { get; } // Stream implements IDisposable
// other properties and methods
}
Run Code Online (Sandbox Code Playgroud)
假设我有一个HttpPostedFile
被调用的实例file
.由于没有Dispose
显式调用的方法,file.InputStream.Dispose()
因此在被破坏之前不会被调用,我认为这与原来的内涵相违背IDisposable
.我认为正确的实现应包含标准IDisposable
实现.因此,如果其中一个成员实现IDisposable
,该类也需要实现它.你有什么看法?这看起来有点复杂.
c# ×4
.net ×3
asp.net ×1
asp.net-mvc ×1
async-await ×1
idisposable ×1
task ×1
throttling ×1
timer ×1
vb.net ×1