I am having a problem with some code which uses Task.Delay. I am probably using it bad because when I try it to wait 2 ms (1000 times) it waits completely different times
My code is
Yes, it is a code for Unity for the Hololens but it uses C#
So when I use Task.Delay(2).Wait the code that should take 2 seconds takes 15 seconds
When I use await.Task.Delay() in the WaitFor2MiliSeconds() function the code that should take 2 seconds takes 0.2 seconds if synchronous or 0.4 if asynchronous
What should I modify in order to wait only 2ms (therefore the fucntion SlowJob taking only 2 seconds)
I will greatly appreciate any help here
My code is
C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
#if !UNITY_EDITOR && UNITY_WSA
using System.Threading.Tasks;
#endif
public class ExampleScript : MonoBehaviour {
// Use this for initialization
void Start () {
Debug.Log("Start():: Starting");
#if !UNITY_EDITOR && UNITY_WSA
// Task.Run( ()=>SlowJob() );
Task.Run( async ()=>SlowJob() ); //Should I put async here?
//SlowJob();
#endif
Debug.Log("Start():: Done");
}
void SlowJob()
{
Debug.Log("ExampleScript::SlowJob() --Doing 1000 things , each taking 2ms");
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
for(int i=0;i<1000;i++)
{
#if !UNITY_EDITOR && UNITY_WSA
//This will require to declare SlowJob to be async
// await Task.Delay(2);
//We use a way that is NOT recommended by experts so we have to be aware of this
// Task.Delay(2).Wait();
//How about this
WaitFor2MiliSeconds();
#endif
}
sw.Stop();
Debug.Log("ExampleScript::SlowJob() --Done! Elapsed Time:" + sw.ElapsedMilliseconds / 1000f);
}
#if !UNITY_EDITOR && UNITY_WSA
private async void WaitFor2MiliSeconds()
{
// await System.Threading.Tasks.Task.Delay(2);
await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(2.0));
}
#endif
}
Yes, it is a code for Unity for the Hololens but it uses C#
So when I use Task.Delay(2).Wait the code that should take 2 seconds takes 15 seconds
When I use await.Task.Delay() in the WaitFor2MiliSeconds() function the code that should take 2 seconds takes 0.2 seconds if synchronous or 0.4 if asynchronous
What should I modify in order to wait only 2ms (therefore the fucntion SlowJob taking only 2 seconds)
I will greatly appreciate any help here
Last edited: