C# 使用小结
语言特性
new 和 override 的区别
c# - Difference between new and override - Stack Overflow
override 表示对虚方法的最终实现
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public override void DoIt()
{
}
}
Base b = new Derived();
b.DoIt(); // Calls Derived.DoIt
new 的话在子类告诉编译器使用此实现。其类型声明指向谁就用谁的实现。
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public new void DoIt()
{
}
}
Base b = new Derived();
Derived d = new Derived();
b.DoIt(); // Calls Base.DoIt
d.DoIt(); // Calls Derived.DoIt
nameof 操作符
用于名称的简单字符串表示
多线程 / 进程
lock
设置临界区。
private static object o = new object();
lock (o )
{
// 要执行的代码逻辑
}
其中的 o 相当于一个锁标识符。所以禁止使用硬编码字符串、Type 和 this 作为锁对象。
禁止在临界区使用 await 语句。因为 await 后面的代码可能由其它进程去执行。通常可以这样做:
lock (foo)
{
}
var result = await something;
lock (foo)
{
}
lock 语句 - C# 参考 | Microsoft Docs
c# - Why is lock(this) {…} bad? - Stack Overflow
Mutex
mutex 可以跨线程(lock 语句不能)
c# - What is the difference between lock and Mutex? - Stack Overflow
I use a Mutex to check see if I already have a copy of the application running on the same machine.
bool firstInstance;
Mutex mutex = new Mutex(false, @"Local\DASHBOARD_MAIN_APPLICATION", out firstInstance);
if (!firstInstance)
{
//another copy of this application running
}
else
{
//run main application loop here.
}
// Refer to the mutex down here so garbage collection doesn't chuck it out.
GC.KeepAlive(mutex);
mutex 同样不兼容 await:c# - My Mutex is not working - Stack Overflow,此时应该使用信号量(Semaphore)。
Semaphore
SemaphoreSlim 是轻量级信号量。参数为容量,每进一个用户,容量减少 1,减少为 0,则等待。可以较好地控制资源的并发数。new SemaphoreSlim (1)
相当于兼容异步的互斥锁。
Interlock
Interlocked 类 (System.Threading) | Microsoft Docs
第三方库
NLog
官网:
文档:Home・NLog/NLog Wiki (github.com)
NLog 的配置文件:NLog.config
只要学会了写 配置文件,就搞定了 80%
Config 布局
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logconsole" />
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>