- Home /
ThreadPool apparently not executing the methods async
Hi guys, I was coding a custom static class for file creation/reading management separated from the Unity engine (I just use Debug.Log int it). This class can read/create file synchronous and asynchronous. The asynchronous tasks are executed by a thread of the ThreadPool. I execute the methods from a class inherited from Monobehaviour. The problem is that I don't think the methods get executed asynchronously.
Here's the code:
public class FileManagement
{
public static void Start()
{
FileManagement.SetupThreadPool();
FileManagement.CreateFileAsync("K\\Hello\\", true, "Hello.txt");
FileManagement.CreateFileAsync("L\\Hello\\", true, "Hello.txt");
FileManagement.CreateFileAsync("C\\Hello\\", true, "Hello.txt");
Debug.Log("Test");
}
public static void SetupThreadPool()
{
int count = Environment.ProcessorCount;
ThreadPool.SetMinThreads(count, count);
count = count + count/2;
ThreadPool.SetMaxThreads(count, count);
}
internal static object lockCFA = new object();
public static void CreateFileAsync(string dir, bool relativeDir, string fileName)
{
lock (lockCFA)
{
WaitCallback callBack = new WaitCallback(_CreateFileAsync);
ThreadPool.QueueUserWorkItem(callBack, new object[] { dir, relativeDir, fileName });
Debug.Log("Test 2");
}
}
private static void _CreateFileAsync(object state)
{
object[] data = state as object[];
CreateFile(data[0] as string, Convert.ToBoolean(data[1]), data[2] as string);
}
internal static object lockCF = new object();
public static void CreateFile(string dir, bool relativeDir, string fileName )
{
if (string.IsNullOrEmpty(dir)) throw new ArgumentNullException("Dir parameter is null or empty.");
if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("FileName parameter is null or empty.");
lock (lockCF)
{
if (relativeDir)
dir = Environment.CurrentDirectory + "\\" + dir;
if (!Directory.Exists(dir))
{
Debug.LogWarning("Warning: Directory " + dir + " doesn't exist");
try
{
Directory.CreateDirectory(dir);
}
catch (Exception e)
{
Debug.LogError(e.StackTrace);
return;
}
}
try
{
FileStream fs = File.Create(dir + fileName, 4096);
fs.Close();
}
catch (Exception e)
{
Debug.Log(e.StackTrace);
return;
}
Debug.Log("Hi 1 , " + Thread.CurrentThread.IsThreadPoolThread.ToString() + ", " + Thread.CurrentThread.ManagedThreadId);
}
}
}
In the Editor's output the logs of CreateFile are always first and the last is always the log "Test", so this tasks are probably not executed async. Is this a coding issue or some Unity thread one ?
P.s. I hope that my english is understandable, I'm not mother tongue
Comment