gpt4 book ai didi

c# - 在控制台应用程序中同步来自不同线程的事件

转载 作者:太空狗 更新时间:2023-10-30 01:09:30 25 4
gpt4 key购买 nike

我感觉自己像个菜鸟问这个问题,但无论如何,就是这样:

我想知道从不同线程同步事件的最简单方法是什么。

一些示例代码:

class Program
{
static void Main(string[] args)
{
Console.WriteLine("# started on:" + Thread.CurrentThread.ManagedThreadId);
tt t = new tt();

t.First += new EventHandler(t_First);
t.Second += new EventHandler(t_Second);

Task task = new Task(new Action(t.Test));
task.Start();

while (true)
{
Console.ReadKey();
Console.WriteLine("# waiting on:" + Thread.CurrentThread.ManagedThreadId);
}
}

static void t_Second(object sender, EventArgs e)
{
Console.WriteLine("- second callback on:" + Thread.CurrentThread.ManagedThreadId);
}

static void t_First(object sender, EventArgs e)
{
Console.WriteLine("- first callback on:" + Thread.CurrentThread.ManagedThreadId);
}

class tt
{
public tt()
{
}

public event EventHandler First;
public event EventHandler Second;

public void Test()
{
Thread.Sleep(1000);

Console.WriteLine("invoked on:" + Thread.CurrentThread.ManagedThreadId);

First(this, null);
Thread.Sleep(1000);
Second(this, null);
}
}
}

正如您可能猜到的,只有第一个 writeline 在主线程上执行,其他调用都在任务创建的新线程上执行。

我想在主线程上同步对“Second”的调用(它永远不会被调用,因为我在 while 循环中阻塞)。但是我想知道这样做的方法或者它是否可能?

最佳答案

你可以试试 BlockingCollection

BlockingCollection<Action> actions = new BlockingCollection<Action>();

void main() {
// start your tasks

while (true) {
var action = actions.Take();

action();
}
}

static void t_First(object sender, EventArgs e) {
string message = "- first callback on:" + Thread.CurrentThread.ManagedThreadId;
actions.Add(_ => Console.WriteLine(message));
}

关于c# - 在控制台应用程序中同步来自不同线程的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6570613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com