111,077
社区成员




private static void Method(object o, MessageClass message)
{
Console.WriteLine(string.Format(@"Class1 对象的属性已经更改,现在的属性是:{0}",message.Message));
Thread t = new Thread(() => Console.WriteLine(String.Format("这个是第二个线程了,也可以使用数据,{0}", message.Message)));
t.Start();
}
少看了,你需要第二个线程来处理变化。只需要在事件相应函数里面启动线程久ok了。
//调用代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static Class1 c;
static void Main(string[] args)
{
c = new Class1();
c.PropertyChanged += Method;//添加事件关注
Thread t = new Thread(()=>Demo());
t.Start();
//主程序结束
Console.ReadKey();
}
//一个线程执行这个方法。修改c的属性
private static void Demo()
{
Thread.Sleep(1000);
Console.WriteLine("thread begin");
c.SetProperty(2);
Console.WriteLine("thread end");
}
//把这个方法添加到c的事件中,触发事件的时候,执行这个方法
private static void Method(object o, MessageClass message)
{
Console.WriteLine(string.Format(@"Class1 对象的属性已经更改,现在的属性是:{0}",message.Message));
}
}
}
//类的信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Class1
{
int _property;
public int GetProperty()
{
return _property;
}
public void SetProperty(int value)
{
_property = value;
OnPropertyChanged(new MessageClass() { ID=1,Message=value.ToString()});
}
protected virtual void OnPropertyChanged( MessageClass message)
{
if (PropertyChanged != null)
{
PropertyChanged(this, message);
}
}
public event EventHandler<MessageClass> PropertyChanged;
}
public class MessageClass
{
public int ID { get; set; }
public string Message { get; set; }
}
}