本帖最后由 陽陽陽 于 2023-8-8 12:03 编辑
这种干货源码网上很难找了,比自己翻资料快,而且还全,源码全部实践验证过+有注释
功能全面,包括一些Thread和Task的冷门功能。
源码:
[C#] 纯文本查看 复制代码 using System;
using System.Threading;
using System.Threading.Tasks;
using System.Dynamic;
using System.Collections.Generic;
namespace TaskExample
{
class Program
{
static void Main(string[] args)
{
TaskCreationOptions_PreferFairness();
Console.ReadLine();
}
public static void Addition_TaskAbortExample()
{
Thread thread = new Thread(() => { Console.WriteLine(1); Thread.Sleep(5000); Console.WriteLine(2); });
thread.Start();
Thread.Sleep(200);
try
{
thread.Abort();
}
catch
{
//因为不再支持,所以……
}
}
public static void Addition_MonitorPulseAllExample()
{
//Easy understand - a Monitor in the Monitor
object obj = new object();
//for (int i = 0; i < 5; i++)
//{
Task t = new Task(() =>
{
Console.WriteLine("entering");
Monitor.Enter(obj);
Console.WriteLine("entered");
Thread.Sleep(5000);
Console.WriteLine("Going to wait");
Monitor.Wait(obj);
Console.WriteLine("waited");
Console.WriteLine("exit");
Monitor.Exit(obj);
});
t.Start();
//}
//Monitor.PulseAll(obj); ///》》》坑:只有获取锁之后才能调用此方法,否则报错《《《Console.WriteLine("exit") ;Monitor.Exit(obj); });
//调用Monitor.Wait(obj)方法时,它会释放对锁对象obj的锁定,并进入等待状态。
Thread.Sleep(2000);
Console.WriteLine("Outside Entering");
Monitor.Enter(obj); //After the Task Wait, it will enter
Console.WriteLine("Outside Entered");
Thread.Sleep(3000);
Console.WriteLine("Outside PulseAll");
Monitor.PulseAll(obj); //Release Wait in Task
Console.WriteLine("Outside Pulsed");
Monitor.Exit(obj);
Console.WriteLine("Outside Exited");
}
public static void TaskDelayExample()
{
Task.Delay(1000).ContinueWith((Task s, object x) => { Console.WriteLine(1); }, null);
var cancellationTokenSource = new CancellationTokenSource();
Thread thread = new Thread(() =>
{
var delayTask = Task.Delay(5000, cancellationTokenSource.Token);
Console.WriteLine(delayTask.IsCanceled);
});
thread.Start();
cancellationTokenSource.Cancel();
}
public static void TaskFacExample()
{
TaskFactory taskFactory = new TaskFactory();
List<Task> ls = new List<Task>();
for (int i = 0; i < 10; i++)
{
int num = i;
ls.Add(taskFactory.StartNew(() => { Thread.Sleep(num * 500); Console.WriteLine($"{num}factroyFinished"); }));
}
taskFactory.ContinueWhenAny(ls.ToArray(), t => { Console.WriteLine(t.AsyncState); });
//会阻塞当前线程:
Task.WaitAny(ls.ToArray());
Console.WriteLine("one finished");
}
public static void TaskWaitExample()
{
Task t = new Task(() => { Thread.Sleep(1000); Console.WriteLine($"Finished"); });
t.Start();
t.Wait();
Console.WriteLine("waited");
}
public static void TaskRunExample()
{
Task task = Task.Run(() => { Console.WriteLine("TaskRunExample"); });
}
public static void RunSynchronouslyExample()
{
Task ta = new Task(() => { Thread.Sleep(5000); });
Console.WriteLine("Outside - 1");
ta.RunSynchronously();
Console.WriteLine("Outside - 2");
}
public static void StatusExample()
{
var tasks = new Task[3];
for (int ctr = 0; ctr <= 2; ctr++)
tasks[ctr] = Task.Run(() => Thread.Sleep(ctr * 500));
Console.WriteLine("Status of all tasks:");
foreach (var t in tasks)
Console.WriteLine(" Task #{0}: {1}", t.Id, t.Status);
//= TaskStatus.Canceled
Console.WriteLine(TaskStatus.RanToCompletion == TaskStatus.WaitingForActivation);
}
public static void Task_T_RestulExample()
{
Task<int> t = new Task<int>(() =>
{ //会获取结果 ≠ 不是异步的。只有在需要结果的时候才会等待。并且等待的时候会消耗CPU
Console.WriteLine("Starting");
Thread.Sleep(20000);
Console.WriteLine("End");
return 100;
});
t.Start();
Console.WriteLine("Here");
Console.WriteLine(t.Result);
}
public static void CancleTokenExample()
{
var tokenSource2 = new CancellationTokenSource();
CancellationToken ct = tokenSource2.Token;
var task = Task.Run(() =>
{
// 我们已经被取消了吗?
ct.ThrowIfCancellationRequested();
bool moreToDo = true;
while (moreToDo)
{
Console.WriteLine("Waiting...");
// 如果你必须做其他清理工作,那么在抛出之前轮询此属性。
if (ct.IsCancellationRequested)
{
//ct.ThrowIfCancellationRequested();
//↑抛出异常
break;
}
Thread.Sleep(20);
}
}, tokenSource2.Token); // 将相同的令牌传递给Task.Run。
Thread.Sleep(2000);
Console.WriteLine("Going to cancle");
tokenSource2.Cancel();
Console.WriteLine("Cancled");
tokenSource2.Dispose();
Console.WriteLine("Finished");
}
public static void CancleTokenExample_Overload()
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var t = Task.Run(() =>
{
for (int i = 0; i < 100000; i++)
{
Console.WriteLine(i);
Thread.Sleep(1);
if (token.IsCancellationRequested)
{
break;
}
}
}, token); //重载在这里
Thread.Sleep(2000);
cts.Cancel();
Console.WriteLine("Finished");
}
public static void TaskCreationOptions_AttachedToParentExample()
{
var parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Parent task beginning.");
var child = Task.Factory.StartNew(() =>
{
Console.WriteLine("Attached child task beginning.");
Thread.Sleep(2000);
Console.WriteLine("Attached child task ending.");
}, TaskCreationOptions.AttachedToParent); //可以自行把第三个参数删掉,可以看到parentTask立即结束
});
parent.Wait();
Console.WriteLine("Parent task ending.");
}
public static void TaskCreationOptions_DenyChildAttach()
{
var parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Parent task beginning.");
var child = Task.Factory.StartNew(() =>
{
Console.WriteLine("Attached child task beginning.");
Thread.Sleep(2000);
Console.WriteLine("Attached child task ending.");
}, TaskCreationOptions.AttachedToParent); //》》》大坑 - 不会报错!!!《《《
}, TaskCreationOptions.DenyChildAttach); //禁止被附加,里面附加不生效
parent.Wait();
Console.WriteLine("Parent task ending.");
}
public static void TaskCreationOptions_PreferFairness()
{
//提示 TaskScheduler 以一种尽可能公平的方式安排任务,
//这意味着较早安排的任务将更可能较早运行,而较晚安排
//运行的任务将更可能较晚运行。
//PS:实际测试好像没啥毛用,反而更混乱:
/*
0
2
1
4
3
5
6
7
8
9
--------------
0
1
2
3
4
5
6
7
8
9
*/
for (int i = 0; i < 10; i++)
{
int number = i;
var t = Task.Factory.StartNew(() =>
{
Console.WriteLine(number);
}, TaskCreationOptions.PreferFairness); //“机器队”
Thread.Sleep(1);
}
Thread.Sleep(2000);
Console.WriteLine("--------------");
for (int i = 0; i < 10; i++)
{
int number = i;
var t = Task.Factory.StartNew(() =>
{
Console.WriteLine(number);
}); //“人工队”
Thread.Sleep(1);
}
}
}
}
vs2019实用功能补充:
如何在多行前面同时加入同样的文本?CtrlCV过时啦:
按住Alt + Shift + ← ,然后向下拖动鼠标,选中多行,再Ctrl+V
不知不觉间,已经可以写正常软件了(尽管很蹩脚)
|