这是创建性能计数器的代码:
var ftpPerfCounter = new PerformanceCounter("FTP Service", "Current Connections", "_Total");
Run Code Online (Sandbox Code Playgroud)
这是异常发生的地方:
int cnt = (int)Math.Round(ftpPerfCounter.NextValue());
Run Code Online (Sandbox Code Playgroud)
这是Exception消息:
"错误消息:指定类别的计数器布局无效,类型的计数器:AverageCount64,AverageTimer32,CounterMultiTimer,CounterMultiTimerInverse,CounterMultiTimer100Ns,CounterMultiTimer100NsInverse,RawFraction或SampleFraction必须紧跟任何基本计数器类型:AverageBase ,CounterMultiBase,RawBase或SampleBase."
错误消息非常神秘.我不知道如何避免将来发生异常.
细节
这种情况发生在Windows Server 2008 R2 64位操作系统上.FTP服务器是IIS.
c# performancecounter invalidoperationexception iis-7.5 windows-server-2008-r2
在他关于C#中线程的优秀论文中,Joseph Albahari提出了以下简单程序来演示为什么我们需要对多个线程读取和写入的数据使用某种形式的内存屏障.如果您在发布模式下编译它并在没有调试器的情况下自由运行它,程序永远不会结束:
static void Main()
{
bool complete = false;
var t = new Thread(() =>
{
bool toggle = false;
while (!complete) toggle = !toggle;
});
t.Start();
Thread.Sleep(1000);
complete = true;
t.Join(); // Blocks indefinitely
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么以上稍微修改过的上述程序版本不再无限期地阻塞?
class Foo
{
public bool Complete { get; set; }
}
class Program
{
static void Main()
{
var foo = new Foo();
var t = new Thread(() =>
{
bool toggle = false;
while (!foo.Complete) toggle = !toggle;
});
t.Start();
Thread.Sleep(1000); …Run Code Online (Sandbox Code Playgroud) 为什么使用 FileOptions.Asynchronous 创建 FileStream 会导致 FileStream.BeginRead 阻塞调用线程?
这是代码片段:
private static Task<int> ReadFileAsync(string filePath)
{
var file = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 64 * 1024, FileOptions.Asynchronous);
FileInfo fi = new FileInfo(filePath);
byte[] buffer = new byte[fi.Length];
Task<int> task = Task<int>.Factory.FromAsync(file.BeginRead, file.EndRead, buffer, 0, buffer.Length, null);
return task.ContinueWith(t =>
{
file.Close();
Console.WriteLine("Done ReadFileAsync, read " + t.Result + " bytes.");
return t.Result;
});
}
Run Code Online (Sandbox Code Playgroud)
当使用 JetBrains dotPeek 深入研究 MSFT FileStream 代码时,他们的代码中似乎存在一个错误:
if (!this._isAsync)
return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
else
return …Run Code Online (Sandbox Code Playgroud) 我有一个"配方"方法,我试图用TDD编写.它基本上会调用不同的方法,偶尔会根据这些方法的结果做出决策:
public void HandleNewData(Data data)
{
var existingDataStore = dataProvider.Find(data.ID);
if (data == null)
return;
UpdateDataStore(existingDataStore, data, CurrentDateTime);
NotifyReceivedData(data);
if (!dataValidator.Validate(data))
return;
//... more operations similar to above
}
Run Code Online (Sandbox Code Playgroud)
我的膝跳反应将是开始编写测试用例,我在其中验证HandleNewData调用上面传递的方法传递预期的参数,并在方法调用失败的情况下返回.但这对我来说有点像这样一个巨大的投入时间来编写这样的测试,几乎没有实际的好处.
那么编写这样的测试真正的好处是什么?还是真的不值得打扰?
看起来它只是一个过度规范的代码,并且只要代码必须调用另一个方法或决定不再调用当前方法之一,就会导致维护问题.
c# ×3
.net ×2
asynchronous ×1
beginread ×1
concurrency ×1
filestream ×1
iis-7.5 ×1
methodology ×1
tdd ×1
unit-testing ×1
volatile ×1