چیست؟
Event Queue یک بافر بین فرستندهها و گیرنده میگذارد. فرستنده Enqueue(request) را صدا میزند و بلافاصله برمیگردد. گیرنده بعداً درخواستها را بیرون میکشد، معمولاً چند درخواست در هر فریم و داخل Update خودش. خود درخواست دادهٔ ساده است، معمولاً یک struct کوچک، نه فراخوانی یک متد.
فرق اصلیاش با Observer و event bus همینجاست: آنها همگام تحویل میدهند، یعنی شنونده همین حالا و داخل call stack فرستنده اجرا میشود. صف فقط اینکه چه کسی پردازش کند را جدا نمیکند؛ زمان پردازش را هم از فرستنده جدا میکند. گیرنده زمانبندی را خودش انتخاب میکند، همهٔ درخواستهای منتظر را میبیند و میتواند قبل از هر کاری آنها را ادغام یا حذف کند.
مثال کلاسیکش در بازی صداست. فرض کن یک نارنجک در یک فریم دوازده دشمن را میکشد و هر کدام PlaySound(EnemyDeath) میخواهد. اگر مستقیم پخش شوند، دوازده کلیپ یکسان روی یک نمونهٔ صوتی شروع میشوند و یک جهش صدای آزاردهنده میسازند. با صف، AudioQueue دوازده درخواست یکسان میبیند، یکی را نگه میدارد و در هر فریم حداکثر maxPerFrame صدا پخش میکند. زیر کاپوت معمولاً یک ring buffer است: آرایهای با اندازهٔ ثابت که اندیسهای head و tail آن دور میزنند، پس در زمان اجرا هیچ حافظهای گرفته نمیشود.
کِی به کار میآید؟
وقتی سراغش برو که فرستندههای زیادی ممکن است در یک بازهٔ کوتاه یک نوع درخواست را پشت سر هم بفرستند و گیرنده باید آنها را هموار، دستهای یا بیتکرار کند: صداها، ساختن جلوههای بصری، عددهای آسیب، پنجرههای آموزشی و پیامهای شبکه.
جایی هم به کار میآید که گیرنده باید با زمانبندی یا thread خودش کار کند: درخواستهای بارگذاری که یکییکی پردازش میشوند، اچیومنتهایی که بعد از فریم مبارزهٔ فعلی باز میشوند، یا کاری که یک job پسزمینه برای main thread میفرستد.
اگر فرستنده جواب لازم دارد یا واکنش باید قبل از خط بعدیاش انجام شود، از آن استفاده نکن. صف بازخورد را ناهمگام میکند و call stack را از دیباگر حذف میکند. پس برای «همین حالا انجامش بده و نتیجه را بگو» یک فراخوانی مستقیم یا event همگام سادهتر است.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// A sender. It asks for sounds but never plays them: Enqueue() returns
/// immediately, even when a grenade kills twelve enemies in one frame.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] private int health = 30;
[SerializeField] private float corpseTime = 1.5f;
public void TakeDamage(int amount)
{
if (health <= 0) return;
health -= amount;
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.Hit, 0.6f));
if (health <= 0)
Die();
}
private void Die()
{
// Twelve of these in one frame still become a single queued request.
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.EnemyDeath));
GetComponent<Collider>().enabled = false;
Destroy(gameObject, corpseTime);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// The receiver. Senders call Enqueue() and return at once; the queue is
/// drained in Update with a per-frame budget, so a burst of requests is
/// merged and spread out instead of hitting the mixer in a single frame.
/// </summary>
public class AudioQueue : MonoBehaviour
{
[SerializeField] private AudioSource source;
[SerializeField] private AudioClip[] clips; // indexed by SoundId
[SerializeField, Min(1)] private int capacity = 8;
[SerializeField, Min(1)] private int maxPerFrame = 2;
public static AudioQueue Instance { get; private set; }
private RingBuffer<PlaySoundRequest> pending;
private void Awake()
{
Instance = this;
pending = new RingBuffer<PlaySoundRequest>(capacity);
}
private void OnDestroy()
{
if (Instance == this) Instance = null;
}
public void Enqueue(in PlaySoundRequest request)
{
// Merge: the same sound is already waiting, so keep one entry at the louder volume.
for (int i = 0; i < pending.Count; i++)
{
ref PlaySoundRequest queued = ref pending[i];
if (queued.Id != request.Id) continue;
if (request.Volume > queued.Volume) queued = request;
return;
}
if (!pending.TryEnqueue(request))
Debug.LogWarning($"AudioQueue full ({pending.Capacity}), dropped {request.Id}", this);
}
private void Update()
{
for (int i = 0; i < maxPerFrame && pending.TryDequeue(out PlaySoundRequest request); i++)
source.PlayOneShot(clips[(int)request.Id], request.Volume);
}
}
}namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// Fixed-capacity FIFO backed by an array. The head index wraps around,
/// so enqueue and dequeue are O(1) and nothing is allocated after construction.
/// </summary>
public class RingBuffer<T> where T : struct
{
private readonly T[] items;
private int head; // index of the oldest pending item
private int count;
public RingBuffer(int capacity) => items = new T[capacity];
public int Count => count;
public int Capacity => items.Length;
public bool IsFull => count == items.Length;
/// <summary>Pending item at offset i from the head, by reference so it can be merged in place.</summary>
public ref T this[int i] => ref items[(head + i) % items.Length];
public bool TryEnqueue(in T item)
{
if (IsFull) return false;
int tail = (head + count) % items.Length;
items[tail] = item;
count++;
return true;
}
public bool TryDequeue(out T item)
{
if (count == 0)
{
item = default;
return false;
}
item = items[head];
items[head] = default;
head = (head + 1) % items.Length;
count--;
return true;
}
}
}namespace Patterns.GameProgramming.EventQueue
{
public enum SoundId
{
Hit,
EnemyDeath,
CoinPickup,
}
/// <summary>
/// One queued message. A small struct with plain data, so enqueuing it
/// never allocates and never keeps a destroyed GameObject alive.
/// </summary>
public readonly struct PlaySoundRequest
{
public readonly SoundId Id;
public readonly float Volume;
public PlaySoundRequest(SoundId id, float volume = 1f)
{
Id = id;
Volume = volume;
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: دشمنهایی که هر کدام همان لحظه صدای مرگ خودشان را پخش میکنند. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
هر prefab دشمن یک AudioSource و دو کلیپ دارد و Enemy داخل TakeDamage و Die مستقیم audioSource.PlayOneShot را صدا میزند.
برای یک دشمن جواب میدهد. ولی وقتی یک نارنجک در یک فریم دوازده دشمن را میکشد، دوازده deathClip یکسان روی یک نمونهٔ صوتی شروع میشوند: میکس اشباع میشود، صدا بلند و درهم میشود و phasing پیدا میکند و هیچ جای واحدی برای محدود یا ادغام کردنشان وجود ندارد.
✓ چه چیزی عوض شد؟
- فیلدهای
audioSource،hitClipوdeathClipحذف شدند؛ دشمن دیگر هیچ تنظیمات صوتیای ندارد. - متدهای
TakeDamageوDieفقطAudioQueue.Instance.Enqueue(new PlaySoundRequest(...))را صدا میزنند و بلافاصله برمیگردند. - کلاس
AudioQueueدرخواستهای باSoundIdیکسان را ادغام میکند و در هر فریم حداکثرmaxPerFrameصدا پخش میکند؛ پس دوازده مرگ یک صدای خوشمیکس میشود.
using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// Without an event queue: every enemy plays its own sounds the moment
/// something happens to it.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] private int health = 30;
[SerializeField] private float corpseTime = 1.5f;
// Every enemy prefab carries its own audio setup.
[SerializeField] private AudioSource audioSource;
[SerializeField] private AudioClip hitClip;
[SerializeField] private AudioClip deathClip;
public void TakeDamage(int amount)
{
if (health <= 0) return;
health -= amount;
audioSource.PlayOneShot(hitClip, 0.6f);
if (health <= 0)
Die();
}
private void Die()
{
// A grenade kills 12 enemies in one frame: 12 identical clips start
// on the same sample and stack into one loud, phasey spike.
audioSource.PlayOneShot(deathClip);
GetComponent<Collider>().enabled = false;
Destroy(gameObject, corpseTime);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// With an event queue: the enemy only asks for sounds. The AudioQueue
/// merges duplicates and plays a limited number per frame.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] private int health = 30;
[SerializeField] private float corpseTime = 1.5f;
public void TakeDamage(int amount)
{
if (health <= 0) return;
health -= amount;
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.Hit, 0.6f));
if (health <= 0)
Die();
}
private void Die()
{
// 12 deaths in one frame are merged into a single queued request.
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.EnemyDeath));
GetComponent<Collider>().enabled = false;
Destroy(gameObject, corpseTime);
}
}
}مزایا و معایب
+ مزایا
- رگبارها هموار میشوند: کار با یک سقف بودجه بین چند فریم پخش میشود، بهجای اینکه یک فریم را منفجر کند.
- گیرنده همهٔ درخواستهای منتظر را میبیند، پس میتواند تکراریها را ادغام کند، اولویت بدهد یا درخواستهای کهنه را دور بریزد.
- فرستندهها و گیرنده از نظر زمانی از هم جدا هستند؛ فرستنده هیچوقت منتظر کد گیرنده نمیماند و آن را اجرا هم نمیکند.
− معایب
- صفِ با اندازهٔ ثابت ممکن است سرریز شود؛ باید تصمیم بگیری درخواست تازه را دور بریزی، قدیمیترین را رونویسی کنی یا صف را بزرگ کنی.
- رسیدگی با تأخیر انجام میشود، پس ممکن است تا زمان پردازش درخواست، دنیا عوض شده باشد (شاید فرستنده دیگر نابود شده باشد).
- دیباگ سختتر میشود: stack trace در لحظهٔ پردازش دیگر نشان نمیدهد چه کسی درخواست را فرستاده است.
چند نکتهٔ کاربردی
- ۰۱داخل درخواست داده بگذار، نه ارجاع. یک
structبا یک شناسهٔ enum و یک موقعیت، بعد از نابود شدن فرستنده هم سالم میماند؛ ارجاع بهGameObjectنه. - ۰۲در زمان توسعه هر درخواست دورریخته را با
Debug.LogWarningثبت کن تا اگر ظرفیت صف کم است، زود متوجه شوی. - ۰۳حواست به حلقههای بازخورد باشد: اگر رسیدگی به یک درخواست میتواند درخواست تازه در صف بگذارد، در هر فریم فقط به تعدادی رسیدگی کن که از اول فریم در صف بودند.
- ۰۴برای کار بین threadها از
System.Collections.Concurrent.ConcurrentQueue<T>استفاده کن؛ یک ring buffer ساده فقط برای یک thread امن است. - ۰۵داخل گیرنده بر اساس کلید (شناسهٔ صدا، هدف) ادغام کن و قویترین مقدار را نگه دار، مثلاً بلندترین volume را، تا درخواست ادغامشده هنوز حس درستی بدهد.