一代軍師
程式語言、理財自我投資、加密貨幣、資訊安全 https://moushih.com/
Action<string> acction = this.doSomething;
AsyncCallback callback = ia => Console.WriteLine($"到這計算完成");
acction.BeginInvoke("btnAsync", callback, null);
//判斷IsCompleted狀態是否結束 如果還沒就讓主執行緒睡覺
while (!asyncResult.IsCompleted)
{
Thread.Sleep(200);
}
asyncResult.AsyncWaitHandle.WaitOne();//等待任務完成
asyncResult.AsyncWaitHandle.WaitOne(-1);//等待任務完成
asyncResult.AsyncWaitHandle.WaitOne(100);//等待任務完成,但最多等待100ms
acction.EndInvoke(asyncResult);//等待任務完成,可以取得委派的返回數值
Func<int> fuck = () =>
{
Thread.Sleep(2000);
return DateTime.Now.Day;
};
Console.WriteLine($"func.Invoke() ={fuck.Invoke()}");
IAsyncResult asyncResult1 = fuck.BeginInvoke(
r =>
{
Console.WriteLine(r.AsyncState);
}, "冰封的心");
Console.WriteLine($"func.EndInvoke(asyncResult1) = {fuck.EndInvoke(asyncResult1)}");
Task.Run(() => this.doSomething("task1"));
TaskFactory taskFactory = Task.Factory;//4.0
taskFactory.StartNew(() => this.doSomething("task3"));
new Task(() => this.doSomething("task5")).Start();
List<Task> taskList = new List<Task>();
taskList.Add(Task.Run(() => this.doSomething("01")));
taskList.Add(Task.Run(() => this.doSomething("02")));
taskList.Add(Task.Run(() => this.doSomething("03")));
taskList.Add(Task.Run(() => this.doSomething("04")));
//阻塞 等者某個任務完成後才會往下進行
Task.WaitAny(taskList.ToArray());//卡介面
//阻塞 等者全部任務完成後才會往下進行
Task.WaitAll(taskList.ToArray());//卡介面
Task.WhenAny(taskList.ToArray()).ContinueWith(t =>
{
Console.WriteLine($"哈哈哈哈:{Thread.CurrentThread.ManagedThreadId}");
});
Task.WhenAll(taskList.ToArray()).ContinueWith(t =>
{
Console.WriteLine($"部屬環境,測試完成 執行緒:{Thread.CurrentThread.ManagedThreadId}");
});
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Thread.Sleep(2000);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Task.Delay(2000).ContinueWith(t =>
{
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
});
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Task.Run(() =>
{
Thread.Sleep(2000);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
});
Parallel.Invoke(() => this.doSomething("test1"),
() => this.doSomething("test1"),
() => this.doSomething("test1"));
Parallel.For(0, 5, i => this.doSomething("第"+i));
Parallel.ForEach(new string[] { "1", "2", "3", "4", "5" },i =>this.doSomething(i));
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = 3;
Parallel.For(0, 5, i => this.doSomething("第" + i));
//Break Stop 都不推荐用
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = 3;
Parallel.For(0, 100, parallelOptions, (i, state) =>
{
if (i == 2)
{
Console.WriteLine("Break,當前線呈結束");
state.Break();//當前線呈結束
return;//必须带上,才會釋放資源
}
if (i == 30)
{
Console.WriteLine("線呈Stop,結束");
state.Stop();//结束Parallel
return;//必须带上,才會釋放資源
}
this.Coding("當前參數", "Client" + i);
});
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = 1;
Parallel.For(1, 100, (i, ParallelLoopState) =>
{
Console.WriteLine($"開始 i => {i} 主要執行續 => {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
if (i == 5)
{
Console.WriteLine($"掰掰 i => {i} 主要執行續 => {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
// 跳出當前執行單元
ParallelLoopState.Stop();
return;//不加return,可能會發生該程序資源未釋放。
}
Console.WriteLine($"結束 i => {i} 主要執行續 => {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
});
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
try
{
for (int i = 0; i < 20; i++)
{
string name = string.Format($"btnThreadCore_Click_{i}");
Action<object> act = t =>
{
Thread.Sleep(2000);
if (t.ToString().Equals("btnThreadCore_Click_11"))
{
throw new Exception(string.Format($"{t} 执行失败"));
}
if (t.ToString().Equals("btnThreadCore_Click_12"))
{
throw new Exception(string.Format($"{t} 执行失败"));
}
Console.WriteLine("{0} 执行成功", t);
};
taskList.Add(taskFactory.StartNew(act, name));
}
}
catch (AggregateException aex)
{
foreach (var item in aex.InnerExceptions)
{
Console.WriteLine(item.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
try
{
for (int i = 0; i < 20; i++)
{
string name = string.Format($"btnThreadCore_Click_{i}");
Action<object> act = t =>
{
Thread.Sleep(2000);
if (t.ToString().Equals("btnThreadCore_Click_11"))
{
throw new Exception(string.Format($"{t} 執行失敗"));
}
if (t.ToString().Equals("btnThreadCore_Click_12"))
{
throw new Exception(string.Format($"{t} 執行失敗"));
}
Console.WriteLine("{0} 執行成功", t);
};
taskList.Add(taskFactory.StartNew(act, name));
}
Task.WaitAll(taskList.ToArray());
}
catch (AggregateException aex)
{
foreach (var item in aex.InnerExceptions)
{
Console.WriteLine(item.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
for (int i = 0; i < 20; i++)
{
string name = string.Format($"btnThreadCore_Click_{i}");
Action<object> act = t =>
{
try
{
Thread.Sleep(2000);
if (t.ToString().Equals("btnThreadCore_Click_11"))
{
throw new Exception(string.Format($"{t} 执行失败"));
}
if (t.ToString().Equals("btnThreadCore_Click_12"))
{
throw new Exception(string.Format($"{t} 执行失败"));
}
Console.WriteLine("{0} 执行成功", t);
}
catch (Exception ex)
{
Console.WriteLine($"Exception:{ex.Message}");
}
};
taskList.Add(taskFactory.StartNew(act, name));
}
Task.WaitAll(taskList.ToArray());
//多个线程并发,某个失败后,希望通知别的线程,都停下来
//task是外部无法中止,Thread.Abort不靠谱,因为线程是OS的资源,无法掌控啥时候取消
//线程自己停止自己--公共的访问变量--修改它---线程不断的检测它(延迟少不了)
//CancellationTokenSource去标志任务是否取消 Cancel取消 IsCancellationRequested 是否已经取消了
//Token 启动Task的时候传入,那么如果Cancel了,这个任务会放弃启动,抛出一个异常
CancellationTokenSource cts = new CancellationTokenSource();//bool值 //bool flag = true;
for (int i = 0; i < 40; i++)
{
string name = string.Format("btnThreadCore_Click{0}", i);
Action<object> act = t =>
{
try
{
//if (cts.IsCancellationRequested)
//{
// Console.WriteLine("{0} 取消一个任务的执行", t);
//}
Thread.Sleep(2000);
if (t.ToString().Equals("btnThreadCore_Click11"))
{
throw new Exception(string.Format("{0} 执行失败", t));
}
if (t.ToString().Equals("btnThreadCore_Click12"))
{
throw new Exception(string.Format("{0} 执行失败", t));
}
if (cts.IsCancellationRequested)//检查信号量
{
Console.WriteLine("{0} 放弃执行", t);
return;
}
else
{
Console.WriteLine("{0} 执行成功", t);
}
}
catch (Exception ex)
{
cts.Cancel();
Console.WriteLine(ex.Message);
}
};
taskList.Add(taskFactory.StartNew(act, name, cts.Token));
}
Task.WaitAll(taskList.ToArray());
for (int i = 0; i < 5; i++)
{
Task.Run(() =>
{
Thread.Sleep(100);
Console.WriteLine(i);
});
}
5
5
5
5
5
for (int i = 0; i < 5; i++)
{
int k = i;
Task.Run(() =>
{
Thread.Sleep(100);
Console.WriteLine(k);
});
}
int TotalCountIn = 0;
for (int i = 0; i < 10000; i++)
{
TotalCountIn++;
}
Console.WriteLine($"TotalCountIn = {TotalCountIn}");
TotalCountIn = 10000
int TotalCountIn = 0;
for (int i = 0; i < 10000; i++)
{
Task.Run(() =>
{
TotalCountIn++;
});
}
Console.WriteLine($"TotalCountIn = {TotalCountIn}");
TotalCountIn = 8972
private static readonly object btnThreadCore_Click_Lock = new object();
lock (btnThreadCore_Click_Lock)
{
}
private static readonly object btnThreadCore_Click_Lock = new object();
void Main()
{
List<Task> taskList = new List<Task>();
int TotalCountIn = 0;
List<int> IntList = new List<int>();
for (int i = 0; i < 10000; i++)
{
int newI = i;
taskList.Add(Task.Run(() =>
{
lock(btnThreadCore_Click_Lock)
{
TotalCountIn+=1;
IntList.Add(newI);
}
}));
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine($"TotalCountIn = {TotalCountIn}");
Console.WriteLine("IntList 總數量為 = " + IntList.Count());
}
TotalCountIn = 10000
IntList 總數量為 = 10000
lock(this)
{
}
void Main()
{
List<Task> taskList = new List<Task>();
int TotalCountIn = 0;
List<int> IntList = new List<int>();
for (int i = 0; i < 10000; i++)
{
int newI = i;
taskList.Add(Task.Run(() =>
{
lock(this)
{
TotalCountIn+=1;
IntList.Add(newI);
}
}));
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine($"TotalCountIn = {TotalCountIn}");
Console.WriteLine("IntList 總數量為 = " + IntList.Count());
}
Monitor.Enter(btnThreadCore_Click_Lock);
要執行的程式
Monitor.Exit(btnThreadCore_Click_Lock);
private static readonly object btnThreadCore_Click_Lock = new object();
void Main()
{
List<Task> taskList = new List<Task>();
int TotalCountIn = 0;
List<int> IntList = new List<int>();
for (int i = 0; i < 10000; i++)
{
int newI = i;
taskList.Add(Task.Run(() =>
{
Monitor.Enter(btnThreadCore_Click_Lock);
TotalCountIn+=1;
IntList.Add(newI);
Monitor.Exit(btnThreadCore_Click_Lock);
}));
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine($"TotalCountIn = {TotalCountIn}");
Console.WriteLine("IntList 總數量為 = " + IntList.Count());
}
int m = 3 + 2;
lock (m) { }//值類型不能lock
string teacher = "Eleven";
string teacherVip = "Eleven";
lock (teacher)
{
}
lock (teacherVip)
{
}