經驗總結23--C#多線程和加鎖

C#的線程蠻簡單。

Thread t1 = new Thread(Runing);
        t.Start();

可以使用匿名線程進行傳參。

Thread t = new Thread(() =>
            {
                Runing();
            });
            t.Start();

這樣的話Runing方法可以使用參數了。

另外如果開了多線程去進行同一個操作,比如寫入文本、數據庫之類的,可以使用加鎖處理。

private static object obj = new object();

 public static void RecordData(string str, string path)
        {
            try
            {
                lock (obj)
                {
                    StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
                    sw.WriteLine(str);
                    sw.Close();//寫入
                }
            }
            catch (Exception e)
            {
                throw new Exception("寫入文件錯誤!");
            }
        }

這樣可以保證都寫入了文件,並比同步效率高,先到先寫入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章