c# 多线程及同步异步问题:
https://www.cnblogs.com/w6w6/p/10648921.html
同步异步代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//异步方法
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine($"***************btnAsync_Click Start {Thread.CurrentThread.ManagedThreadId}");
Action<string> action = this.DoSomethingLong;
// 调用委托(同步调用)
//action.Invoke("btnAsync_Click_1");
// 异步调用委托
action.BeginInvoke("btnAsync_Click_2", null, null);
for (int i = 0; i < 5; i++)
{
string name = string.Format($"btnSync_Click_{i}");
// this.DoSomethingLong(name);
action.BeginInvoke(name, null, null);
}
Console.WriteLine($"***************btnAsync_Click End {Thread.CurrentThread.ManagedThreadId}");
}
//同步方法
//等待上一步操作执行完,在进行下一步操作
private void button2_Click(object sender, EventArgs e)
{
Console.WriteLine($"****************btnSync_Click Start {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
int j = 3;
int k = 5;
int m = j + k;
for (int i = 0; i < 5; i++)
{
string name = string.Format($"btnSync_Click_{i}");
this.DoSomethingLong(name);
}
}
private void DoSomethingLong(string name)
{
Console.WriteLine($"****************DoSomethingLong {name} Start {Thread.CurrentThread.ManagedThreadId.ToString("00")} { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
long lResult = 0;
for (int i = 0; i < 1000000000; i++)
{
lResult += i;
}
Console.WriteLine($"****************DoSomethingLong {name} End {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {lResult}***************");
}
}
}
异步运行结果:
同步运行结果:
delegate及Aciton、Func的异同:
https://www.cnblogs.com/xuxiaoshuan/p/6844511.html