【发布时间】:2012-02-20 06:43:09
【问题描述】:
我需要在 Windows 应用程序中实现带宽限制功能。 SO上有两个线程:
- How to programatically limit bandwidth usage of my c# windows forms application
- Bandwidth throttling in C#
但这是针对网络应用程序的。我需要它用于 Windows 应用程序。 如何在 Windows 中实现它? 我可以将上述链接用于 Windows 应用程序吗?
这是我正在使用的代码:
// Apply bandwidth control
int uploadLimit = GlobalClass.GetFileUploadLimit();
if (uploadLimit > 0)
{
long bps = uploadLimit * 1024;
const int BufferSize = 8192;
MemoryStream mstream = new MemoryStream();//Stream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize);
// Openup source stream.
using (FileStream sourceStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize))
{
// Create throttled destination stream.
ThrottledStream destinationStream = new ThrottledStream(mstream, bps);
byte[] buffer = new byte[BufferSize];
int readCount = sourceStream.Read(buffer, 0, BufferSize);
while (readCount > 0)
{
destinationStream.Write(buffer, 0, readCount);
readCount = sourceStream.Read(buffer, 0, BufferSize);
client.FileUpload(Convert.ToInt16(userId), System.IO.Path.GetFileName(fileName), buffer);
//Webservice: Here is the problem
}
}
}
在上面的代码中,有一个我用来上传文件的网络服务。此 Web 服务一次以字节为单位获取整个文件。所以在这种情况下,我不能分块上传文件。任何人都可以建议我以某种方式来完成此任务,或者我是否应该更改服务以分块接受数据?
【问题讨论】:
-
您发布的第二个链接包含指向 ThrolledStream 示例的链接。这应该适用于您的 Windows 应用程序。
-
我使用了链接中的相同节流类。请看我上面的代码。
-
上传的代码不是你写的,显然你无法改变它的工作方式。
标签: c# windows-applications bandwidth-throttling