[C#] How to write Task in V2?

Hey, I want to write this command, but I dont understand how to use Coroutines instead of Tasks:

Natives.RegisterCommand("dv", new Action<int, object[], string>( async(source, args, raw) =>
            {
                Ped Ped = Game.PlayerPed;

                if (Ped.IsInVehicle())
                {
                    Vehicle CurrentVeh = Ped.CurrentVehicle;
                    CurrentVeh.Delete();
                }else if (args.Length > 0)
                {
                    Vehicle[] Vehicles = World.GetAllVehicles();
                    await Task.Run(() =>
                    {
                        for (int i = 0; i < Vehicles.Length; i++)
                        {
                            Vehicle Vehicle = Vehicles[i];
                            if (World.GetDistance(Vehicle.Position, Ped.Position) < (float)args[0])
                            {
                                Vehicle.Delete();
                            }
                        }
                    });
                }
            }), false);

The error:

1SCRIPT ERROR in handling function reference: Basics.Client.Commands+<>c.<.ctor>b__0_1
[    388094] [FiveM_b2802_GT]             MainThrd/ 	with arguments: (System.Byte, System.Object[], System.String): System.MethodAccessException: Error verifying Basics.Client.Commands/<>c/<<-ctor>b__0_1>d:MoveNext (): Method System.Threading.Tasks.Task:Run (System.Action) is not accessible at 0x0069^7
[    388094] [FiveM_b2802_GT]             MainThrd/   at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine] (TStateMachine& stateMachine) [0x0002c] in <b575c7ac070e41ffa0751333b6ac9f42>:0 

[    388094] [FiveM_b2802_GT]             MainThrd/   at Basics.Client.Commands+<>c.<.ctor>b__0_1 (System.Int32 source, System.Object[] args, System.String raw) [0x0001c] in <68a0ba6ae3af46e09c8c1f8d4f2366d3>:0 

[    388094] [FiveM_b2802_GT]             MainThrd/   at (wrapper dynamic-method) System.Object:Basics.Client.Commands+<>c.<.ctor>b__0_1 (object,CitizenFX.Core.Remote,object[])

[    388094] [FiveM_b2802_GT]             MainThrd/   at CitizenFX.Core.ReferenceFunctionManager.Invoke (System.Int32 reference, System.Byte* arguments, System.UInt32 argsSize) [0x00024] in C:\gl\builds\master\fivem\code\client\clrcore-v2\Interop\ReferenceFunctionManager.cs:175 

There is no API solving this setup yet, I’ll add a feature request myself to support Coroutine.Run.

For now you may use the following instead:

  1. Lambda
Func<Coroutine> lambda = async () =>
{
	// your async code
};

await lambda();
  1. Lambda written smaller
await new Func<Coroutine>(async () =>
{
	// your async code
})();
  1. Method (can be placed in method bodies)
async Coroutine Method()
{
	// your async code
};

await Method();

* these are options, not an advice, pick the one you like

1 Like

Btw you can register commands with the [Command("my_command")] attribute on BaseScripts, will look nicer.

1 Like