C#中如何提高静态事件线程安全? [英] How to raise a static event thread safe in C#?

查看:128
本文介绍了C#中如何提高静态事件线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以提出一个静态事件线程安全吗? (我不完全确定这甚至是什么意思)
整个事情都是音频应用程序的一部分,所以我至少拥有音频处理线程和UI线程。



RaisePrintEvent从非托管C代码调用,处理音频和其他消息。调用事件可以从音频处理线程和UI线程发生。

  public static event ProcessPrint Print = delegate { }; 

private static void RaisePrintEvent(string e)
{
Print(e);
}

如何确保事件调用同步?或者也许只是在主线程中调用。



编辑:在这里阅读一个智能解决方案

解决方案

您必须确保UI操作全部在主/ UI线程上执行。



最好的方法是将消息从音频线程排队到某种形式的队列中,并出现,并从主UI线程显示,例如从 Forms.Timer 事件。



Invoke()不会让你远,因为您的音频处理时间将被打破。如果你尝试它,并且你正在用GUI来做某事,那么你可能会在音频中跳动,因为Invoke() - 其他线程上的东西将BLOCK直到其他线程处理用于做Invoke的窗口消息



如果您不了解上述部分或全部内容,只需尝试使用队列作为消息。


Can i raise a static event thread safe? (i am not entirely sure what that even means.) The whole thing is part of an audio application, so i have (at least) the audio processing thread and the UI thread.

The RaisePrintEvent gets invoked from unmanaged C code which processes the audio and other messages. The call to raise the event can happen from the audio processing thread and the UI thread.

public static event ProcessPrint Print = delegate {};

private static void RaisePrintEvent(string e)
{
    Print(e);
}

How can i make sure, that the event call is synchronized? Or maybe just invoked in the main thread..

EDIT: read on here for a smart solution.

解决方案

You must ensure that the UI operations are all executed on the main/UI thread.

Best way would be to queue the messages into some form of queue from the audio thread and dequeue and display it from main UI thread, from Forms.Timer event, for example.

Invoke() won't get you far because your timing in the audio processing will be broken. If you try it, and you are doing something with your GUI, you'll probably get jerking in the audio, since Invoke()-ing something on other thread will BLOCK until other thread process the window message that is used to do Invoke 'under the hood'.

If you don't understand some or all of the above, just try to use queue for the messages.

这篇关于C#中如何提高静态事件线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆