进行事件1的时候,可以同时进行事件2
假如有一个烧水的动作,从0-100。我们要在stripbar中显示进度。同时还不能堵塞主线程
为了架构具有拓展性,我们在这里使用事件模式来驱动
首先新建一个事件类,包含 水温这个属性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 观察者模式跨线程调用控件
{
public class ValueArgs:EventArgs
{
public int value { get; set; }
}
}
其次 我们建立烧水这个对象,里面包含 烧水这个动作,烧水这个动作里会调用我们设定的event
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 观察者模式跨线程调用控件
{
class WaterTemperature
{
public delegate void BoilWaterEventHandler(Object sender,ValueArgs e);
public event BoilWaterEventHandler temperatureChanged;
protected void OnValuechanged(ValueArgs e)
{
if(temperatureChanged!=null)
{
temperatureChanged(this,e);
}
}
public void BoilWater()
{
for(int i=0;i<=100;i++)
{
Thread.Sleep(100);
ValueArgs e = new ValueArgs() { value = i };
this.OnValuechanged(e);
}
}
}
}
这样的话,我们可以在调用方法的时候,给类的事件赋值,如果还需要其他动作,可以加载多个事件。具有拓展性
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 观察者模式跨线程调用控件
{
public partial class Form1 : Form
{
WaterTemperature work = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
work.temperatureChanged += changeProcess;
Action obj = new Action(work.BoilWater);
obj.BeginInvoke(BoilWaterCallBack, "我这个是回调状态");
bk1.RunWorkerAsync();
}
public void BoilWaterCallBack(IAsyncResult result)
{
Console.WriteLine(result.AsyncState.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
work = new WaterTemperature();
}
public void changeProcess(object send,ValueArgs e)
{
Action delobj = () => this.progressBar1.Value = e.value;
if (this.progressBar1.InvokeRequired)
{
this.progressBar1.Invoke(delobj);
}else
{
delobj();
}
Func<string,int> fuobj = (x) => { int y = Convert.ToInt32(x); return y; };
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("......");
}
}
}