关于C#事件

zkhj 2011-04-24 05:17:10
我希望在函数执行完成后,发出一个事件,应该如何做
...全文
97 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xieyang702 2011-04-24
  • 打赏
  • 举报
回复
private delegate void ddtDelegate();

static void Main(string[] args)
{
ddtDelegate ddt = new ddtDelegate(OnFinished);
ddt();
}

public static void OnFinished()
{
Console.WriteLine("Finished!");
//Console.ReadLine();
}
这是我认为最好理解的代码了,呵呵,因为我也是初学者
threenewbee 2011-04-24
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wuyazhe 的回复:]
和事件有关么?

C# code
public void Test()
{
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
{
……
[/Quote]
对哦,如果不使用MT,不存在异步问题,根本没必要事件。
laichunlin 2011-04-24
  • 打赏
  • 举报
回复
用委托和事件

private delegate void ddtDelegate(string str);
private ddtDelegate ddt;

private void 要执行的函数(string str)
{
...
ddt(str);
}

在要发生该事件的地方注册一下该事件 如果在同一类中,则在构造函数中

ddt+=new ddtDelegate(Instance_ddt);

private void Instance_ddt(string str)
{
message.show(str);
}
兔子-顾问 2011-04-24
  • 打赏
  • 举报
回复
和事件有关么?
public void Test()
{
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("方法异步执行完了");
};
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync();//启动线程去执行方法

//同步执行就更简单了。
worker_DoWork(null, null);
Console.WriteLine("同步函数执行完毕。");
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("执行方法");
}
threenewbee 2011-04-24
  • 打赏
  • 举报
回复
你可以绑定多个委托:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Action action = () => Console.WriteLine("Finished1.");
action += () => Console.WriteLine("Finished2.");
action += () => Console.WriteLine("Finished3.");
foo(action);
}

static void foo(Action callback)
{
Console.WriteLine("Do something in foo.");
callback();
}
}
}
threenewbee 2011-04-24
  • 打赏
  • 举报
回复
也可以这么调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foo(() => { Console.WriteLine("Finished!"); });
}

static void foo(Action callback)
{
Console.WriteLine("Do something in foo.");
callback();
}
}
}
threenewbee 2011-04-24
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foo(OnFinished);
}

static void OnFinished()
{
Console.WriteLine("Finished!");
}

static void foo(Action callback)
{
Console.WriteLine("Do something in foo.");
callback();
}
}
}
zilong4460072 2011-04-24
  • 打赏
  • 举报
回复
用委托就可以了

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧