在上几章我们讨论了方法属性字段的aspect,现在我们再来看看事件机制的aspect。和字段,属性location一样,在c#中字段也可以转化为方法名为add,remove的方法处理,所以对于事件的aspect,同样类似于我们的方法。我们先看看EventInterceptionAspect的定义:
为我们提供了,ProceedAddHandler,ProceedInvokeHandler,ProceedRemoveHandler的事件处理代理。同样包含来自AdviceArgs的Instance对象。
[Serializable]
public class AsynEventAspectAttribute : PostSharp.Aspects.EventInterceptionAspect
{
public override void OnInvokeHandler(PostSharp.Aspects.EventInterceptionArgs args)
{
var th =
new System.Threading.Thread(
new System.Threading.ParameterizedThreadStart(
new Action<
object>((obj) =>
{
System.Threading.Thread.Sleep(
new Random().Next(
1000));
try {
args.ProceedInvokeHandler();
}
catch (Exception ex)
{
args.ProceedRemoveHandler();
}
})));
th.Start();
}
}
namespace PostSharpDemo
{
public class TestAsyncAspect
{
[AsynEventAspectAttribute]
public event EventHandler SomeEvent =
null;
public void OnSomeEvent()
{
if (SomeEvent !=
null)
{
SomeEvent(
this, EventArgs.Empty);
}
}
}
}
class Program
{
static void Main(
string[] args)
{
TestAsyncAspect pro =
new TestAsyncAspect();
for (
int i =
0; i <
10; i++)
{
pro.SomeEvent +=
new EventHandler(pro_SomeEvent);
}
pro.OnSomeEvent();
// pro.SomeEvent -= new EventHandler(pro_SomeEvent); Console.WriteLine(
" 主线程完了! ");
Console.Read();
}
static void pro_SomeEvent(
object sender, EventArgs e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
}
}