static void Main(string[] args)
{
test();
Console.WriteLine(".......按任意键退出");
Console.ReadKey();
}
static async void test()
{
var p1 = Task.Run(async () =>
{
await Task.Delay(1000);
Console.WriteLine("p1");
});
var p2 = Task.Run(async () =>
{
await Task.Delay(800);
Console.WriteLine("p2");
});
await p1;
await p2;
}
//-------------------------------------------------------------------------------------------------------------------------
Dim h As IHTMLDocument2
h = CType(ie1.Document.DomDocument, IHTMLDocument2)
MsgBox(ie1.Document.InvokeScript("eval", New Object() {"document.querySelector('input.s_ipt').value"}))
'MsgBox(h.parentWindow.InvokeScript("function fio(){return document.querySelector('input.s_ipt').value;}"))
//-------------------------------------------------------------------------------------------------------------------------
Public Class Form1
Public WithEvents cls As Class1
Private Sub xxxxxxx(value As Integer) Handles cls.ValueChanged
Me.Invoke(Sub()
TextBox1.Text = value.ToString()
End Sub)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cls.Run()
End Sub
End Class
Public Class Class1
Public Event ValueChanged(value As Integer)
Public Sub Run()
Task.Run(Sub()
Dim x As Integer = 0
For i As Integer = 1 To 55
x += 1
RaiseEvent ValueChanged(x)
Threading.Thread.Sleep(1000)
Next
End Sub)
End Sub
End Class
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Imports System
Module Program
Sub Main(args As String())
AddHandler X.啊哈, AddressOf xx
X.test("aaa")
Console.WriteLine("按任意键结束......")
Console.ReadKey()
End Sub
Sub xx(x As String)
Console.WriteLine(x)
End Sub
End Module
Module X
Public Event 啊哈(a As String)
Sub test(a As String)
RaiseEvent 啊哈(a)
End Sub
End Module
//-------------------------------------------------------------------------------------------------------------------------
<System.Runtime.CompilerServices.Extension> _
Public Function MyTrim(ByVal s As Long) As String '参数是什么类型,就是什么类型的附加函数
Return If(s = 0, 1, 2)
End Function
//-------------------------------------------------------------------------------------------------------------------------
List<string> ListA = new List<string>();
List<string> ListB = new List<string>();
List<string> ListResult = new List<string>();
ListResult = ListA.Distinct().ToList();//去重
ListResult = ListA.Except(ListB).ToList();//差集
ListResult= ListA.Union(ListB).ToList();//并集
ListResult = ListA.Intersect(ListB).ToList();//交集
Take(n) - 获取集合的前n个元素
Skip(n) - 跳过集合的前n个元素
Dim L1, L2 As New List(Of String)
L1 = Split("1,2,3,4,5,2", ",").ToList
L2 = Split("1,2,a,b,c,2", ",").ToList
L1 = L1.Where(Function(s) Trim(s) <> "").Select(Function(s) s.Trim).Intersect(L2.Select(Function(s) s.Trim()), StringComparer.OrdinalIgnoreCase).ToList
//-------------------------------------------------------------------------------------------------------------------------
Format(Ctype(string,Date),"yyyy-MM-dd HH:mm:ss") //必须转成date才可以转换格式!!!!
//-------------------------------------------------------------------------------------------------------------------------
Dim L1 As New List(Of String) From {"1", "1", "3"}
Dim L2 As New List(Of String) From {"a", "b", "c"}
Dim res = L1.Concat(L2)
Dim ress = L1.Concat(L2).Distinct()
Console.WriteLine(String.Join(vbCrLf, ress)) '先合并然后去重复
//-------------------------------------------------------------------------------------------------------------------------
Dim L1 As New List(Of String) From {"1", "2", "3"}
Dim L2 As New List(Of String) From {"a", "b", "c"}
Console.WriteLine(String.Join(vbCrLf, (From x In L1, y In L2 Select (y & x))))
a1 a2 a3 b1 b2 b3 c1 c2 c3
//-------------------------------------------------------------------------------------------------------------------------
Dim dirInfo As New DirectoryInfo(bufferDataPath)
Dim files = dirInfo.GetFiles
'Linq
Dim csvFiles= From item In files Where item.Extension = ".csv" Select item
'Lambda
Dim csvFiles = files.Where(Function(item) item.Extension = ".csv").ToList
//-------------------------------------------------------------------------------------------------------------------------
Imports System.Threading
Module Module1
Dim cancelSource As CancellationTokenSource = New CancellationTokenSource(6000)
Sub Main()
CancelTask()
Console.WriteLine(TimeOfDay & " Async Run ")
Thread.Sleep(2000)
cancelSource.Cancel() '取消指令,但是Task内还是继续执行
'cancelSource.CancelAfter(1000)
Console.Read()
End Sub
Public Sub CancelTask()
Task.Run(Sub()
Do
Thread.Sleep(1000)
Console.WriteLine(TimeOfDay & " Task over " & cancelSource.IsCancellationRequested)
Loop Until cancelSource.IsCancellationRequested '取消执行一发出,IsCancellationRequested就转true
End Sub, cancelSource.Token)
cancelSource.Token.Register(Sub() Console.WriteLine(TimeOfDay & " Task cancel ")) '取消立即执行/不取消到最大等待时间时执行
Console.WriteLine("~~~~")
End Sub
End Module
//-------------------------------------------------------------------------------------------------------------------------
static void Main(string[] args)
{
int studentCount = 10;
int seatCount = 4;//小小食堂只有4个位子
var semaphore = new SemaphoreSlim(seatCount, seatCount);
var eatings = new Task[studentCount];
for (int i = 0; i < studentCount; i++)
{
eatings[i] = Task.Factory.StartNew(() => Eat(semaphore));
}
Task.WaitAll(eatings);
Console.WriteLine("All students have finished eating!");
Console.Read();
}
static void Eat(SemaphoreSlim semaphore)
{
semaphore.Wait();
try
{
Console.WriteLine("Student {0} is eating now!", Task.CurrentId);
Thread.Sleep(1000);
}
finally
{
Console.WriteLine("Student {0} have finished eating!", Task.CurrentId);
semaphore.Release();
}
}
//-------------------------------------------------------------------------------------------------------------------------
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
//-------------------------------------------------------------------------------------------------------------------------
Action<> 没有返回值,<>里全是参数类型
Func<> 必有返回值,<>里除了最后1个是返回值类型,前面全是对应的参数类型
//-------------------------------------------------------------------------------------------------------------------------
MessageBox.Show(Properties.Resources.ole);
string st = Properties.Resources.ResourceManager.GetString("ole");
value = Properties.Resources.ResourceManager.GetObject(fileName, Properties.Resources.Culture)
public static Bitmap GetImageByName(string imageName)
{
System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
string resourceName = asm.GetName().Name + ".Properties.Resources";
var rm = new System.Resources.ResourceManager(resourceName, asm);
return (Bitmap)rm.GetObject(imageName);
}
//-------------------------------------------------------------------------------------------------------------------------
Public Sub New()
InitializeComponent()
backgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If BackgroundWorker1.IsBusy <> True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If BackgroundWorker1.WorkerSupportsCancellation = True Then
' Cancel the asynchronous operation.
BackgroundWorker1.CancelAsync()
End If
End Sub
' This event handler is where the time-consuming work is done.
Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim i As Integer
For i = 1 To 10
If (worker.CancellationPending = True) Then
e.Cancel = True
Exit For
Else
' Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500)
worker.ReportProgress(i * 10)
End If
Next
End Sub
' This event handler updates the progress.
Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
TextBox1.Text = (e.ProgressPercentage.ToString() + "%")
End Sub
' This event handler deals with the results of the background operation.
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
TextBox1.Text = "Canceled!"
ElseIf e.Error IsNot Nothing Then
TextBox1.Text = "Error: " & e.Error.Message
Else
TextBox1.Text = "Done!"
End If
End Sub
//-------------------------------------------------------------------------------------------------------------------------
Dim action As Action(Of String) = Sub(s)
'MsgBox(s)
End Sub
Task.Factory.StartNew(Sub() action("alpha")).ContinueWith(Sub() action("beta")).ContinueWith(Sub() action("gamma")).Wait()
Dim negate As Func(Of Integer, Integer, Integer) = Function(n, m)
MsgBox(n, , m)
'Thread.Sleep(1000)
Return -n
End Function
Task.Factory.StartNew(Function() negate(5, 1)).
ContinueWith(Function(antecendent) negate(antecendent.Result, antecendent.Result)).
ContinueWith(Function(antecendent) negate(antecendent.Result, antecendent.Result)).Wait()
Task(Of Integer).Factory.StartNew(Function() negate(6, 10)).
ContinueWith(Sub(antecendent) action(antecendent.Result.ToString())).
ContinueWith(Function(antecendent) negate(7, 10)).
Wait()
//-----------------------------------------------------------------------------------------------------------------------------------------------
Dim tasks As New List(Of Task)()
Dim rnd As New Random()
Dim lockObj As New Object()
Dim words6() As String = {"reason", "editor", "rioter", "rental",
"senior", "regain", "ordain", "rained"}
For Each word6 In words6
Dim t As New Task(Sub(word)
Dim chars() As Char = word.ToString().ToCharArray()
Dim order(chars.Length - 1) As Double
SyncLock lockObj
For ctr As Integer = 0 To order.Length - 1
order(ctr) = rnd.NextDouble()
Next
End SyncLock
Array.Sort(order, chars)
//-----------------------------------------------------------------------------------------------------------------------------------------------
Imports System.Threading
Imports System.Threading.Timer
Public Class Form1
Dim aaa As System.Threading.Timer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
aaa = New System.Threading.Timer(AddressOf xxx, Nothing, 0, 200)
End Sub
Private Sub xxx(ByVal s As Object)
Me.Invoke(Sub() Me.Label1.Text = Val(Me.Label1.Text) + 1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
aaa.Dispose()
End Sub
End Class
Console.WriteLine("{0} --> {1}", word,
New String(chars))
End Sub, word6)
t.Start()
t.ContinueWith(Sub() Console.WriteLine("-------------"))
tasks.Add(t)
Next
Task.WaitAll(tasks.ToArray())
Console.ReadLine()
//-----------------------------------------------------------------------------------------------------------------------------------------------
Public Class Form1
Dim cq As ConcurrentQueue(Of String)
Dim bc As BlockingCollection(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim j As Integer, pd As Boolean, s As String
'bc = New BlockingCollection(Of String)
cq = New ConcurrentQueue(Of String)
For j = 0 To 1
Dim t = Task.Factory.StartNew(
Sub()
Dim ss As String = ""
Do
pd = cq.TryDequeue(ss)
If pd Then
Me.Invoke(Sub() ListBox1.Items.Add(ss))
Thread.Sleep(10)
Else
'Exit Do
End If
Loop
End Sub
)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'ListBox1.Items.Clear()
Dim j As Integer, pd As Boolean, s As String
Dim L As New List(Of Task)
For j = 0 To 2
Dim t = Task.Factory.StartNew(Sub(j2)
For i = 1 To 3
cq.Enqueue(j2 & "-" & i)
Next
End Sub, j
)
L.Add(t)
Next
Task.WaitAll(L.ToArray)
End Sub
End Class
============================================================================================================
Dim gcAction As Action = Sub()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
'----------------------------
Dim ac As New Action(Sub()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub)
ac()
'--------------------------
Array.ForEach(New String() {"xx", "mm", "-r"}, action)
Dim action As New Action(Of String)(AddressOf DPrintString)
Private Sub DPrintString(s As String)
Debug.Print(s)
End Sub
============================================================================================================
Dim _cts As CancellationTokenSource = New CancellationTokenSource()
Dim po = New ParallelOptions()
po.CancellationToken = _cts.Token
po.MaxDegreeOfParallelism = 20
Dim aa() As Action
ReDim aa(16)
For i As Integer = 0 To aa.Length - 1
Dim ii = i
aa(i) = New Action(Sub() MsgBox(ii))
Next
Parallel.Invoke(po, aa)
============================================================================================================
Imports System.Collections.Concurrent
Imports Microsoft.VisualBasic
Imports System.Threading.Tasks
Imports System.Threading
Public Class Form1
Dim bc As BlockingCollection(Of String)
Dim bc_cancel As Boolean
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Show()
Me.Invoke(Sub() ListBox1.Items.Clear())
bc = New BlockingCollection(Of String)()
For j = 0 To 1
Dim t = Task.Factory.StartNew(Sub()
Do
Dim s As String = "", pd As Boolean
pd = bc.TryTake(s)
If pd Then Me.Invoke(Sub() ListBox1.Items.Add(s)) : Thread.Sleep(666)
Loop Until bc_cancel
MsgBox("~~")
End Sub)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim j As Integer
Dim L As New List(Of Task)
Me.Invoke(Sub() ListBox1.Items.Clear())
For j = 0 To 2
Dim t = Task.Factory.StartNew(Sub(jj)
For i = 0 To 2
Do Until bc.TryAdd(jj & "-" & i)
Loop
Next
End Sub, j
)
L.Add(t)
Next
Task.WaitAll(L.ToArray)
'bc.CompleteAdding()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim ss As String = ""
bc_cancel = True
Do : Loop Until Not bc.TryTake(ss)
bc_cancel = False : bc = Nothing
Me.Invoke(Sub() ListBox1.Items.Clear())
bc = New BlockingCollection(Of String)()
For j = 0 To 2
Dim t = Task.Factory.StartNew(Sub()
Do
Dim s As String = "", pd As Boolean
pd = bc.TryTake(s)
If pd Then Me.Invoke(Sub() ListBox1.Items.Add(s)) : Thread.Sleep(666)
Loop Until bc_cancel
End Sub)
Next
End Sub
End Class
============================================================================================================以下是独立线程,每个timer开始都会创建1个新线程,最开始会等待.Interval毫秒
Imports System.Threading
'Imports System.Threading.Timer
Imports System.Timers.Timer
Public Class Form1
Dim aaa As System.Timers.Timer
Dim t As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
aaa = New System.Timers.Timer()
aaa.Interval = 500
aaa.Enabled = True
AddHandler aaa.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf xxx)
t = System.Environment.TickCount
End Sub
Private Sub xxx()
Me.Invoke(Sub()
Me.Label1.Text = Val(Me.Label1.Text) + 1
Dim a = System.Environment.TickCount - t
Me.Text = a & "|" & (a / Val(Me.Label1.Text))
End Sub)
Thread.Sleep(5000)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
aaa.Enabled = False
End Sub
End Class
============================================================================================================以下是独立线程,每个timer开始都会创建1个新线程,最开始不会等待.Interval毫秒
Imports System.Threading
Imports System.Threading.Timer
'Imports System.Timers.Timer
Public Class Form1
Dim aaa As System.Threading.Timer
Dim t As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
t = System.Environment.TickCount
aaa = New System.Threading.Timer(AddressOf xxx, Nothing, 0, 3000)
End Sub
Private Sub xxx(ByVal ob As Object)
Me.Invoke(Sub()
Me.Label1.Text = Val(Me.Label1.Text) + 1
Dim a = System.Environment.TickCount - t
Me.Text = a & "|" & (a / Val(Me.Label1.Text))
End Sub)
Thread.Sleep(1000)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
aaa.Dispose() : aaa = Nothing
End Sub
End Class
//----------------------------------------------------------------------------------------------------------------------------------------------
private bool Process(FileInfo x)
{
var result = File.ReadAllText(x.FullName).Contains("a");
if (result)
this.listBox1.BeginInvoke((Action)delegate
{
this.listBox1.Items.Add("文件:" + x.FullName);
});
return result;
}
private void button1_Click(object sender, EventArgs e)
{
this.button1.Enabled = false;
this.listBox1.Items.Clear();
var start = new DirectoryInfo(@"C:\Net_test\Windows_c\Windows_c\");
ThreadPool.QueueUserWorkItem(h =>
{
var n = (from x in start.EnumerateFiles("*.txt", SearchOption.AllDirectories).AsParallel() where (Process(x)) select x).Count();
});
}
//----------------------------------------------------------------------------------------------------------------------------------------------
static void Main(string[] args)
{
Console.WriteLine("---------------------" + Thread.CurrentThread.ManagedThreadId);
//Action<string> action = new Action<string>(fio);
Func<string, string> func = new Func<string,string>(s => //Func<参数1,参数2,返回值> 因为Func必须有返回值,所以只有1个参数的时候就是返回值
{ //Action<参数1,参数2> 因为Action必须无返回值,所以全是参数
Thread.Sleep(2000);
return "i love ole" + s;
});
AsyncCallback asyn = new AsyncCallback(r => {
string s_result = func.EndInvoke(r);
Console.WriteLine(s_result);
Thread.Sleep(3000);
Console.WriteLine(r.AsyncState + "----asyn-----" + Thread.CurrentThread.ManagedThreadId);
});
//IAsyncResult a = action.BeginInvoke("beginInvoke-----" + Thread.CurrentThread.ManagedThreadId, asyn,"fiole");
IAsyncResult a = func.BeginInvoke(" For EVER!!!!!!",asyn, "fiole");
//a.AsyncWaitHandle.WaitOne(-1);
//a.AsyncWaitHandle.WaitOne(100);
//while (!a.IsCompleted) {
// Thread.Sleep(10);
//}
//action.EndInvoke(a);
//string s_result = func.EndInvoke(a);
Console.WriteLine("END-----" + a.AsyncState + "-----" + Thread.CurrentThread.ManagedThreadId);
Console.Read();
}
static void fio(string s) {
Console.WriteLine(s);
}
//----------------------------------------------------------------------------------------------------------------------------------------------
static void Main(string[] args)
{
Action<string> a = new Action<string>((s) => { Console.WriteLine(s); });
a("i love ole");
Func<string, string, string> f = new Func<string, string, string>((s1, s2) => { Console.WriteLine(s1 + s2); return s1 + s2 + "!"; });
var ss = f("fi","ole");
Console.WriteLine(ss);
Func<string> funcValue = delegate
{
return "我是即将传递的值3";
};
DisPlayValue(funcValue);
DisPlayValue(new Func<string>(() => { return "我是即将传递的值3"; }));
Console.Read();
}
private static void DisPlayValue(Func<string> func)
{
string RetFunc = func();
Console.WriteLine("我在测试一下传过来值:{0}", RetFunc);
}
//----------------------------------------------------------------------------------------------------------------------------------------------
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
scriptruntime py = IronPython.hosting.python.createruntime();
dynamic obj = py.UseFile("hello.py");
console.WriteLine(obj.welcome("wwww!"));
//----------------------------------------------------------------------------------------------------------------------------------------------
正则平衡组,匹配相等的{ 和 }
\{((?<o>\{)|(?<-o>)\}|[^{}]+)*(?(o)(?!))\}
正则平衡组,匹配相等的{"title":"和 }
\{"title":"((?<o>\{)|(?<-o>)\}|[^{}]+)*(?(o)(?!))\}
Dim reg = Regex.Matches(x, "\{""title"":""((?<o>\{)|(?<-o>)\}|[^{}]+)*(?(o)(?!))\}")
TextBox1.Text = reg.Item(0).ToString()
//----------------------------------------------------------------------------------------------------------------------------------------------
//C# 的高效方法取得图片的像素区数据
Bitmap image = (Bitmap)pictureBox1.Image;
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * image.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
Marshal.Copy(ptr, rgbValues, 0, bytes);
// Unlock the bits.
image.UnlockBits(bmpData);
return rgbValues;
//----------------------------------------------------------------------------------------------------------------------------------------------
string bb = "BCAx";
string aa = "AABBBCCC";
var r = bb.SelectMany(x => aa.Where(y => x == y)).GroupBy(y => y).OrderByDescending(x => x.Count());
var cc = string.Join("", r.Select(y => y.Key));
Console.WriteLine(cc);
//----------------------------------------------------------------------------------------------------------------------------------------------
string bb = "ABC";
string aa = "AABBBCCCC";
ConcurrentDictionary<string, int> cd = new ConcurrentDictionary<string, int>();
Parallel.For(0,aa.Length , i => {
var s = aa.Substring(i, 1);
cd.AddOrUpdate(s, 1, (key, value) => {
return value += 1;
});
});
//cd.AddOrUpdate()里的s,1的s是key,1是要改变的增值,具体怎么增在后面的() => {} 里设置
//----------------------------------------------------------------------------------------------------------------------------------------------
var threadTwo = new Thread(Count);
是创建一个线程,准备调用 Count 方法
threadTwo.Start(8); 才是执行,并传递参数 8
var threadThree = new Thread(() => CountNumbers(12));
是创建一个线程,准备调用匿名方法 () => CountNumbers(12)
//----------------------------------------------------------------------------------------------------------------------------------------------
Sub Main()
Dim t(10) As Task
For index = 0 To 10
Dim i = index
t(index) = New Task(Function()
Dim s = fio(i)
Return s & "------------"
End Function)
t(index).Start()
Next
'For i = 0 To 10
' Dim ii = i
' t(i) = Task.Factory.StartNew(Function() As String
' Dim s = fio(ii)
' Return s & "="
' End Function)
'Next
Task.WaitAll(t)
Console.ReadKey()
End Sub
Function fio(ByVal s As String) As String
s += "|ole"
Console.WriteLine(s)
Return s
End Function
//----------------------------------------------------------------------------------------------------------------------------------------------
static void a() { Console.WriteLine("a"); }
static void b() { Console.WriteLine("b"); }
static void c() { Console.WriteLine("c"); }
static void Main(string[] args)
{
Action someFun = new Action(a);
someFun += b;
someFun += c;
foreach (Action action in someFun.GetInvocationList())
{
//Code to exit these functions
action.Invoke();
}
Console.ReadKey();
}
//----------------------------------------------------------------------------------------------------------------------------------------------
\b(?!un)\w+(?<!un)\b 提取所有不以un开头和结尾的单词
//----------------------------------------------------------------------------------------------------------------------------------------------
Task<string> taskGetResult = Task<string>.Factory.StartNew(WriteSomethingAgain,(object)"");
static string WriteSomethingAgain(object param)
{
for (int i = 0; i < 6; i++)
{
Console.WriteLine("write:" + i);
Thread.Sleep(100);
param = (string)param + i.ToString();
}
return (string)param;
}
//----------------------------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace TaskDemo
{
class Program
{
static void Main(string[] args)
{
CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
Task task = Task.Factory.StartNew(Do, cancelTokenSource.Token, cancelTokenSource.Token);
Thread.Sleep(1000);
try
{
cancelTokenSource.Cancel();
Thread.Sleep(10);
task.Wait();
}
catch (Exception ex)
{
if (task.IsCanceled)
{
Console.WriteLine("ERR! Task has been canceled" + "\r\n" + ex.Message);
}
}
finally
{
task.Dispose();
cancelTokenSource.Dispose();
}
Console.WriteLine("Exiting Main...");
Console.ReadKey();
}
static void Do(object cancelToken)
{
for (int i = 0; i < 100; i++)
{
if (((CancellationToken)cancelToken).IsCancellationRequested)
{
Console.WriteLine("Cancel han been requested");
return;
//注释break,去掉下面注释,程序会抛出异常,通过异常取消代码接收到取消事件发生。
//token.ThrowIfCancellationRequested();
}
Console.WriteLine(i);
Thread.Sleep(500);
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------------------------------
None
指定应使用默认行为。
PreferFairness
提示 TaskScheduler 以一种尽可能公平的方式安排任务,这意味着较早安排的任务将更可能较早运行,而较晚安排运行的任务将更可能较晚运行。
LongRunning
指定某个任务将是运行时间长、粗粒度的操作。 它会向 TaskScheduler 提示,过度订阅可能是合理的。
AttachedToParent
指定将任务附加到任务层次结构中的某个父级。
//---------------------------------------------------------------------------------------------------------------------------------------------/
private void button1_Click_1(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
checkedListBox1.Items.Add("x" + i);
}
}
private void button2_Click(object sender, EventArgs e)
{
var pd = !checkedListBox1.GetItemChecked(0);
for (int i = 0; i < 10; i++)
{
checkedListBox1.SetItemChecked(i, pd);
}
}
private void button3_Click(object sender, EventArgs e)
{
string s = null;
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
//s += checkedListBox1.CheckedItems[i].ToString() + "\r\n";
s += checkedListBox1.GetItemText(checkedListBox1.CheckedItems[i]) + "\r\n";
}
MessageBox.Show(s );
}
private void button4_Click(object sender, EventArgs e)
{
for (int i = 0; i < 2; i++)
{
MessageBox.Show(checkedListBox1.GetSelected(i).ToString ()); //是否当前鼠标选中行
}
}
private void button5_Click(object sender, EventArgs e)
{
//checkedListBox1.Items.Clear();
//checkedListBox1.Items.RemoveAt(checkedListBox1.Items.Count);
checkedListBox1.Items.Remove(checkedListBox1.Items[0].ToString()); //只删除第一个符合的
}
private void button6_Click(object sender, EventArgs e)
{
if (checkedListBox1.SelectedIndex != -1)
{
MessageBox.Show(checkedListBox1.Items[checkedListBox1.SelectedIndex].ToString());
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------/
folderBrowserDialog1.SelectedPath = System.Environment.CurrentDirectory;
//folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyDocuments;
folderBrowserDialog1.ShowNewFolderButton = true;
folderBrowserDialog1.Description = "请选择一个文件夹";
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(folderBrowserDialog1.SelectedPath);
}
//---------------------------------------------------------------------------------------------------------------------------------------------/
public partial class Form1 : Form
{
public AppSettings appset;
public Form1()
{
InitializeComponent();
propertyGrid1.Size = new Size(300, 250);
appset = new AppSettings();
propertyGrid1.SelectedObject = appset;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(appset.ItemsInMRUList.ToString ());
}
}
public class AppSettings
{
private bool saveOnClose = true;
private string greetingText = "欢迎使用应用程序!";
private int itemsInMRU = 4;
private int maxRepeatRate = 10;
private bool settingsChanged = false;
private string appVersion = "1.0";
public bool SaveOnClose
{
get { return saveOnClose; }
set { saveOnClose = value; }
}
public string GreetingText
{
get { return greetingText; }
set { greetingText = value; }
}
public int MaxRepeatRate
{
get { return maxRepeatRate; }
set { maxRepeatRate = value; }
}
public int ItemsInMRUList
{
get { return itemsInMRU; }
set { itemsInMRU = value; }
}
public bool SettingsChanged
{
get { return settingsChanged; }
set { settingsChanged = value; }
}
public string AppVersion
{
get { return appVersion; }
set { appVersion = value; }
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------/
List<string> L1 = new List<string>();
List<string> L2 = new List<string>();
List<string> L3 = new List<string>();
//-----------------------------------------------------------------------------------------------------------------------------------------------
L1.Add("1");
L1.Add("2");
L1.Add("1");
L2.Add("a");
L2.Add("b");
L2.Add("1");
L1.AddRange(L2); //只简单追加L2到L1后
L3 = L1.Concat(L2).ToList<string>(); //*同上
L3 = L1.Union(L2).ToList<string>(); //追加后总体上去重
L3 = L1.Except(L2).ToList<string>(); //在L1里去掉L2里有的然后导出
L1.Sort();
MessageBox.Show(L1.BinarySearch("1").ToString ()); //只能用于排序后查询,速度超快
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
Task<int> t = new Task<int>(() => Add(cts.Token), cts.Token);
t.Start();
t.ContinueWith(TaskEnded);
//等待按下任意一个键取消任务
Console.ReadKey();
cts.Cancel();
Console.ReadKey();
}
static void TaskEnded(Task<int> task)
{
Console.WriteLine("任务完成,完成时候的状态为:");
Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
Console.WriteLine("任务的返回值为:{0}", task.Result);
}
static int Add(CancellationToken ct)
{
Console.WriteLine("任务开始……");
int result = 0;
while (!ct.IsCancellationRequested)
{
result++;
Thread.Sleep(1000);
}
return result;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
//等待按下任意一个键取消任务
TaskFactory taskFactory = new TaskFactory();
Task[] tasks = new Task[3];
for (int i = 0; i < 3; i++)
{
//tasks[i] = new Task(() => Add(cts.Token));
tasks[i] = Task.Factory.StartNew(() => Add(cts.Token));
//tasks[i] = (new TaskFactory()).StartNew (() => Add(cts.Token));
//tasks[i] = taskFactory.StartNew(() => Add(cts.Token));
//tasks[i].Start();
}
//CancellationToken.None指示TasksEnded不能被取消
taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None );
Console.ReadKey();
cts.Cancel();
Console.ReadKey();
}
static void TasksEnded(Task[] a)
{
Console.WriteLine("所有任务已完成!");
}
static void Add(CancellationToken token)
{
Console.WriteLine("!");
}
--------------------------------------------------------------------------------
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
//等待按下任意一个键取消任务
TaskFactory taskFactory = new TaskFactory();
Task[] tasks = new Task[]
{
taskFactory.StartNew(() => Add(cts.Token)),
taskFactory.StartNew(() => Add(cts.Token)),
taskFactory.StartNew(() => Add(cts.Token))
};
//CancellationToken.None指示TasksEnded不能被取消
taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None);
Console.ReadKey();
cts.Cancel();
Console.ReadKey();
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lordeo.Framework;
using System.IO;
namespace c_form12
{
class A
{
public string 编号;
public DateTime 日期;
public TimeSpan 时间;
public double 数值;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static List<A> 读取(FileInfo file, DateTime 日期)
{
using (var fr = new StreamReader(file.FullName))
{
var res = new List<A>();
while (!fr.EndOfStream)
{
var line = fr.ReadLine();
if (line.Trim() != string.Empty)
{
var cs = line.Split(','); //这部分调用你自己的解析程序,这里只是示例
res.Add(new A
{
编号 = cs[0],
日期 = 日期,
时间 = TimeSpan.Parse(cs[1]),
数值 = double.Parse(cs[2])
});
}
}
return res;
}
}
private void button1_Click(object sender, EventArgs e)
{
var 日期 = DateTime.Now.Date;
var dir = new DirectoryInfo("D:\\1\\datas_" + 日期.ToString("yyyyMMdd"));
if (dir.Exists)
{
var result = (from file in dir.EnumerateFiles().AsParallel()
from data in 读取(file, 日期) select data).ToList();
MessageBox.Show(result.Count.ToString());
}
}
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Show();
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost/"); //添加需要监听的url范围
while (true) {
listener.Start(); //开始监听端口,接收客户端请求
label1.Text = "Listening...";
//阻塞主函数至接收到一个客户端请求为止
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = string.Format("<HTML><BODY> iloveole {0}</BODY></HTML>", DateTime.Now);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
//对客户端输出相应信息.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
//关闭输出流,释放相应资源
output.Close();
}
//listener.Stop(); //关闭HttpListener
}
}
}