尝试使用线程在后台保存文件 [英] Trying to use threads to save a file in the background

查看:67
本文介绍了尝试使用线程在后台保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我尝试使用线程在后台保存文件,以防止主统一线程在保存文件之前冻结:

So I am trying to use threads to save a file in the background to prevent the main unity thread from freezing until the file is saved:

public void SaveMap() {
  MapRendererBehaviour mapRendererBehaviour = GameObject.FindWithTag("MapRenderer").GetComponent<MapRendererBehaviour>();
  SerializedMap serializedMap = mapRendererBehaviour.ToSerializedData();

  Debug.Log("test");
  _saveMapThread = new Thread(() => {
    string saveMapJson = JsonConvert.SerializeObject(serializedMap);

    File.WriteAllText(_saveMapFilePath, saveMapJson);
  });
}

出于某种原因,线程代码似乎没有执行,因为文件没有被保存.如果我注释掉线程创建并只将线程的主体留在那里,则文件会正确保存.

For some reason the thread code does not seem to be executing because the file is not getting saved. If I comment out the thread creation and just leave the body of the thread in there, the file saves properly.

任何人都知道我在这里可能做错了什么(我认为我在做一些愚蠢的事情,因为我以前从未尝试过使用线程).

Anyone know what I might be doing wrong here (I assume I am doing something dumb as I have never tried to use threads before).

推荐答案

这可能是一头雾水,但如果您使用的是命名线程而不是任务,您通常必须在之后说 ThreadName.Start() ,例如在之后声明线程说:

This might be a shot in the dark but if you are using named threads instead of tasks you normally have to say ThreadName.Start() after so for example after declaring the thread say:

_saveMapThread.Start();

这篇关于尝试使用线程在后台保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆