c# Beginlnvoke 委托
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; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public delegate void deletask(int num1, int num2); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { deletask task = new deletask(test); int num30 = int.Parse(this.textBox1.Text); int num40 = int.Parse(this.textBox2.Text); task.BeginInvoke(num30, num40, null, null); } private void test(int num1, int num2) { int sum = 0; for (int i = num1; i <= num2; i++) { sum += num1; num1++; } this.label1.Text = sum.ToString(); } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } } }
c# 委托线程返回值 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; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public delegate int deletask(int num1, int num2); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { deletask task = test; int num3 = int.Parse(this.textBox1.Text); int num4 = int.Parse(this.textBox2.Text); //task.BeginInvoke(num3, num4, null, null); IAsyncResult res = task.BeginInvoke(num3, num4, null, null); int result = task.EndInvoke(res); this.label1.Text = result.ToString(); } private int test(int num1, int num2) { int sum = 0; for (int i = num1; i <= num2; i++) { sum += num1; num1++; } return sum; } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } } }