WebGLThreadingPatcher icon indicating copy to clipboard operation
WebGLThreadingPatcher copied to clipboard

Question: Consider alternative

Open MHDante opened this issue 3 years ago • 8 comments

Hey, I was quite fond of finding this package, however, It seems a bit brittle to modify the IL directly. It falls strictly into the realm of "dark magic" 🧙

I've achieved similar success by calling the dispatch method myself:

using System;
using System.Reflection;
using System.Threading;
using UnityEngine;

public static class WebGlThreadPoolPumper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
    public static void StartPumping()
    {
        if (Application.platform != RuntimePlatform.WebGLPlayer || Application.isEditor) return;

        var dispatchMethod = Type
            .GetType("System.Threading.ThreadPoolWorkQueue")?
            .GetMethod("Dispatch", BindingFlags.NonPublic | BindingFlags.Static)?
            .CreateDelegate(typeof(Func<bool>)) as Func<bool>;

        Pump(dispatchMethod);
    }

    public static void Pump(object dispatchMethod)
    {
        var method = (Func<bool>)dispatchMethod;
        var didFinishWork = method();
        SynchronizationContext.Current.Post(Pump, dispatchMethod);
    }
}

However, this may not be as robust as your solution. In particular, I'm not sure I understand why the timer callback is necessary. (is it for time-sensitive callbacks?)

MHDante avatar Dec 10 '21 10:12 MHDante

Hi! in fact, it's a great option but my intention was to mimic mono-wasm ThreadPool behaviour. It included updated code for GetMinThreads, GetMaxThreads, SetMinThreads, SetMaxThreads and GetAvailableThreads. Also, my wanted to rewrite System.Threading.Timer but I have used your solution to run System.Threading.Timers in newer versions of Unity 😄

VolodymyrBS avatar Jun 21 '22 09:06 VolodymyrBS

Also, I'm thinking about commenting all "dark magic" methods with the example code that they generate and how they do it.

VolodymyrBS avatar Jun 21 '22 09:06 VolodymyrBS

This is off-topic, but @VolodymyrBS emitting raw IL to patch mscorlib is a feat of engineering you rarely ever see. You, sir, are an artist of the highest abilities. I'm a huge fan 🤯 .

olokobayusuf avatar Jul 19 '22 23:07 olokobayusuf

This is off-topic, but @VolodymyrBS emitting raw IL to patch mscorlib is a feat of engineering you rarely ever see. You, sir, are an artist of the highest abilities. I'm a huge fan 🤯 .

My thoughts exactly. 😊 I really appreciate the effort!

xucian avatar Jul 26 '22 09:07 xucian

Also, I'm thinking about commenting all "dark magic" methods with the example code that they generate and how they do it.

any blog artic for us to learn this dark magic ,栓 q~

Bian-Sh avatar Nov 07 '22 02:11 Bian-Sh

I could not get this implementation to work for me with 2023+

StephenHodgson avatar Jun 03 '23 21:06 StephenHodgson