C# Trick -3
1.Lambda 与 匿名函数
(x, y) => x * y //多参数,隐式类型=> 表达式
x => x * 5 //单参数, 隐式类型=>表达式
x => { return x * 5; } //单参数,隐式类型=>语句块
(int x) => x * 5 //单参数,显式类型=>表达式
(int x) => { return x * 5; } //单参数,显式类型=>语句块
() => Console.WriteLine() //无参数
bs.fundelegate = (int i)=> {
print("i am lambda "+i);
};
bs.fundelegate += delegate (int i)//匿名函数1
{
print("i am delegate() "+i);
};
bs.fundelegate += delegate//匿名函数2
{
print("i am delegate ");
};
19. delegate
delegate void Del();
static void Main()
{
Del del=delegate
{
Console.WriteLine("Hello world ");
}
del();
}
public delegate int Del(int x);
Del del1 = delegate(int x) {return x+1;};//匿名方法
Del del2= (int x) => {return x+1;};//Lambda表达式
Del del3= (x) => {return x+1;}
Del del4= x => x+1;
20.
Task.Delay(millisecondsTimeout).RunSynchronously();
public delegate void ThreadStart();
public static void StartThread(ThreadStart threadStart)
{
Task.Factory.StartNew(o => ((ThreadStart)o)(), threadStart);
}
2.
ReadAsync.asTask
3 Trace
/// <summary>
/// Tracing levels
/// </summary>
public enum TraceLevel
{
Error = 0x01,
Warning = 0x02,
Information = 0x04,
Verbose = 0x0F,
Frame = 0x10,
Queuing = 0x20
}
// delegate for writing trace
public delegate void WriteTrace(string format, params object[] args);
/// <summary>
/// Tracing class
/// </summary>
public static class Trace
{
public static TraceLevel TraceLevel;
public static WriteTrace TraceListener;
[Conditional("DEBUG")]
public static void Debug(string format, params object[] args)
{
if (TraceListener != null)
{
TraceListener(format, args);
}
}
public static void WriteLine(TraceLevel level, string format)
{
if (TraceListener != null && (level & TraceLevel) > 0)
{
TraceListener(format);
}
}
public static void WriteLine(TraceLevel level, string format, object arg1)
{
if (TraceListener != null && (level & TraceLevel) > 0)
{
TraceListener(format, arg1);
}
}
public static void WriteLine(TraceLevel level, string format, object arg1, object arg2)
{
if (TraceListener != null && (level & TraceLevel) > 0)
{
TraceListener(format, arg1, arg2);
}
}
public static void WriteLine(TraceLevel level, string format, object arg1, object arg2, object arg3)
{
if (TraceListener != null && (level & TraceLevel) > 0)
{
TraceListener(format, arg1, arg2, arg3);
}
}
}
3.
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
Interlocked.Read(ref _sentPacketsCount);
Interlocked.Read(ref _sentPacketsCount);
MqttClientKeepAliveMonitor(string clientId, Func<Task> keepAliveElapsedCallback, IMqttNetChildLogger logger)