【问题标题】:Invoking a function in main thread via background thread in Unity通过 Unity 中的后台线程调用主线程中的函数
【发布时间】:2021-10-09 14:24:45
【问题描述】:

我正在使用以下代码在后台从服务器检索数据。

new Thread(retrieveData()).Start();

下面是从服务器接收数据的函数,

void retrieveData()
{
    while (true)
    {
        string data = subSocket.ReceiveFrameString();
       
    }
}

我想根据从服务器接收到的数据创建一个预制件。不幸的是,我不能从使用retrieveData 的后台线程中这样做。如何向主线程发送回调并在指定位置创建预制件?

【问题讨论】:

  • 在主线程上创建 Handler 并在其上创建 post(Runnable) ...

标签: c# multithreading unity3d backgroundworker


【解决方案1】:

可能有多种方法。

最常用的是所谓的“主线程调度程序”模式,可能看起来像例如

// An object used to LOCK for thread safe accesses
private readonly object _lock = new object();
// Here we will add actions from the background thread
// that will be "delayed" until the next Update call => Unity main thread
private readonly Queue<Action> _mainThreadActions = new Queue<Action>();

private void Update () 
{
    // Lock for thread safe access 
    lock(_lock)
    {
        // Run all queued actions in order and remove them from the queue
        while(_mainThreadActions.Count > 0)
        {
            var action = _mainThreadActions.Dequeue();

            action?.Invoke();
        }
    }
}

void retrieveData()
{
    while (true)
    {
        var data = subSocket.ReceiveFrameString();
   

        // Any additional parsing etc that can still be done on the background thread

        // Lock for thread safe access
        lock(_lock)
        {
            // Add an action that requires the main thread
           _mainThreadActions.Enqueue(() =>
            {
                // Something that needs to be done on the main thread e.g.
                var text = new GameObject("Info").AddComponent<Text>();
                text.text = Data;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多