C# Notes

Constraints on Type Parameters

Constraint Description
where T: struct The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types for more information.
where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.
where T :<base class name> The type argument must be or derive from the specified base class.
where T :<interface name> The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.
where T : U The type argument supplied for T must be or derive from the argument supplied for U.

See for details

MemoryMappedFile

For IPC(Inter-Process Communication) use.

About Unit Test Code Coverage

Methods to be tested should be directly called by TestMethod in unit test project.

Regex - match number groups from string

var matches = new Regex(@"([0-9]+)").Matches(sourceString); //() : group; [0-9] : number; + : one or more times.
var result = new List<int>();
for (int i = 0; i < matches.Count; i++)
{
        result.Add(int.Parse(matches[i].Groups[1].Value));
}
return result ;

Add Sorted Item to List

see original article

public static void AddSorted<T>(this IList<T> list, T item, IComparer<T> comparer = null)
{
    if (comparer == null)
        comparer = Comparer<T>.Default;

    int i = 0;
    while (i < list.Count && comparer.Compare(list[i], item) < 0)
        i++;

    list.Insert(i, item);
}

What's the differences between Task.Run and Task.Factory.StartNew

So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the new Task.Run method. This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters. It’s a shortcut. In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters. When you pass an Action to Task.Run:

Task.Run(someAction);

that’s exactly equivalent to:

Task.Factory.StartNew(someAction, 
    CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

For instance:
lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.

One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:

Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);

see reference

Linq Select() notice

Thinking about these codes below:

//update method signiture from MyDataService:  bool UpdateModel(string id);
var updateResults = MyViewModels.Select(vm => MyDataService.UpdateModel(vm.Model.Id));
if (updateResults.Any(r => r))
{
  //if at least one update done, notify user.
}

If there're more than 1 MyViewModel here, and the first is updated successfully, then the other Models will not be updated. The reason is that Any() is called to execute Select() sequence and the first condition has been satisfied. So here we'd better use a ToList() append to Select().

Signal

  • SemaphoreSlim
SemaphoreSlim _ss = new SemaphoreSlim(1); //Synchronously only 1 await execution to go
public async Task<string> Request()
{
    await _ss.WaitAsync(); // compare with Wait(), it's asynchronous.
    var response = await request.GetResponseAsync();
    _ss.Release();
}

  • EventWaitHandle (no asynchronous operation)
EventWaitHandle _ew = new EventWaitHandle(false, EventResetMode.AutoReset);//initialState is false and reset automatically
public void ShowOneThingForAWhile(string message, int millisecond)
{
    if (ShowNotification)
        _ew .Set();
    Message = message;
    ShowNotification = true;
    Task.Run(() => {
        _ew .WaitOne(millisecond); //will reset automatically here
        ShowNotification = false;
    });
}

Asynchronous != Multi-threads

JavaScript milliseconds and C# DateTime converters

public static class DateTimeExtensions
{
    public static readonly DateTime DtUtc1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long ToJSMilliseconds(this DateTime dt)
    {
        return ((dt.ToUniversalTime().Ticks - DtUtc1970.Ticks) / 10000);
    }

    public static DateTime? ParseJSMilliseconds(this string totalMilliseconds)
    {
        long ms;
        if (!long.TryParse(totalMilliseconds, out ms)) return null;
        DateTime dt = DtUtc1970.AddMilliseconds(ms).ToLocalTime();
        return dt;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市看尼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌上煤,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件著淆,死亡現(xiàn)場離奇詭異劫狠,居然都是意外死亡,警方通過查閱死者的電腦和手機永部,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門独泞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人苔埋,你說我怎么就攤上這事懦砂。” “怎么了组橄?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵孕惜,是天一觀的道長。 經(jīng)常有香客問我晨炕,道長,這世上最難降的妖魔是什么毫炉? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任瓮栗,我火速辦了婚禮,結果婚禮上瞄勾,老公的妹妹穿的比我還像新娘费奸。我一直安慰自己,他們只是感情好进陡,可當我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布愿阐。 她就那樣靜靜地躺著,像睡著了一般趾疚。 火紅的嫁衣襯著肌膚如雪缨历。 梳的紋絲不亂的頭發(fā)上以蕴,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機與錄音辛孵,去河邊找鬼丛肮。 笑死,一個胖子當著我的面吹牛魄缚,可吹牛的內容都是我干的宝与。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼冶匹,長吁一口氣:“原來是場噩夢啊……” “哼习劫!你這毒婦竟也來了?” 一聲冷哼從身側響起嚼隘,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤诽里,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后嗓蘑,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體须肆,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年桩皿,在試婚紗的時候發(fā)現(xiàn)自己被綠了豌汇。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡泄隔,死狀恐怖拒贱,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情佛嬉,我是刑警寧澤逻澳,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站暖呕,受9級特大地震影響斜做,放射性物質發(fā)生泄漏。R本人自食惡果不足惜湾揽,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一瓤逼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧库物,春花似錦霸旗、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至民晒,卻和暖如春精居,著一層夾襖步出監(jiān)牢的瞬間锄禽,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工箱蟆, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留沟绪,地道東北人唠亚。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓霹俺,卻偏偏與公主長得像焊傅,于是被迫代替她去往敵國和親瓶竭。 傳聞我的和親對象是個殘疾皇子立轧,可洞房花燭夜當晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內容

  • 時間開始變得深刻尚揣,因為在每一刻的它的流逝中翠拣,我們感受到了真實存在的自己闸英。
    加菲貓is胖紙閱讀 170評論 0 0