【发布时间】:2021-05-20 14:18:05
【问题描述】:
我想测试是否可以使用在新任务中工作的方法触发事件。
当我这样做时:
using System;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
subscriber f = new subscriber();
}
}
class subscriber
{
publisher x;
public subscriber()
{
x = new publisher();
x.ThresholdReached += c_ThresholdReached;
x.method2();
}
static void c_ThresholdReached(object sender, EventArgs e)
{
Console.WriteLine("The threshold was reached.");
}
}
class publisher
{
public event EventHandler ThresholdReached;
public publisher()
{
}
public void method1()
{
OnThresholdReached(EventArgs.Empty);
}
public void method2()
{
Task.Run(() => method1());
}
protected virtual void OnThresholdReached(EventArgs e)
{
EventHandler handler = ThresholdReached;
handler?.Invoke(this, e);
}
}
}
输出什么都没有!
但是,当我这样做时:
using System;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
subscriber f = new subscriber();
}
}
class subscriber
{
publisher x;
public subscriber()
{
x = new publisher();
x.ThresholdReached += c_ThresholdReached;
x.method2();
}
static void c_ThresholdReached(object sender, EventArgs e)
{
Console.WriteLine("The threshold was reached.");
}
}
class publisher
{
public event EventHandler ThresholdReached;
public publisher()
{
}
public void method1()
{
OnThresholdReached(EventArgs.Empty);
}
public void method2()
{
//Here is the change
method1();
Task.Run(() => method1());
}
protected virtual void OnThresholdReached(EventArgs e)
{
EventHandler handler = ThresholdReached;
handler?.Invoke(this, e);
}
}
}
输出是这样的:
The threshold was reached
The threshold was reached
这很奇怪! 我不明白为什么它会打印两次。
但是,我排除了它不适用于 method1 在新任务中运行,因为它不会在同一个线程中工作
有人能解释一下为什么吗? 有没有办法与父线程通信并发方法?
提前致谢
【问题讨论】:
-
第一个代码不打印任何内容,因为
Main方法在method1执行之前结束,这使得控制台应用程序在打印消息之前关闭。 -
在
Main中添加Console.ReadKey();让控制台等待输入。
标签: c# asynchronous task