locked
windows phone上使用 async await 多线程同步 写日志问题? RRS feed

  • 问题

  • windows phone  8.1 上我会有写日志操作 ,写文进都是异步操作,同时代码中使用了多线程,

    这样当我用如下方法写日志时,当有多线程操作时,会经常抛异常 SaveLogFile Error,这是因为写文件时只能同时有一个操作。

    如果我用变量标识,来避免这样的情况,会出现日志丢失的情况。这样的问题如何来解决?

     public static async Task SaveLogFile(string logData)
     {
                Debug.WriteLine(logData);
                try
                {
                 
                            logFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(SysLog.LOGFOLDERNAME, CreationCollisionOption.OpenIfExists);
                            string logFileName = GenerateLogFileName();
                            logFile = await logFolder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists);
                        }
                        using (IRandomAccessStream outStream = await logFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            Stream s = outStream.AsStreamForWrite();
                            s.Seek(0, SeekOrigin.End);
                            byte[] readBuffer = Encoding.UTF8.GetBytes(logData + "\r\n");
                            await s.WriteAsync(readBuffer, 0, readBuffer.Length);
                            await s.FlushAsync();
                    }
                }
                catch (Exception ex)
                {
                    Log("SaveLogFile Error", ex.Message);
                }
            }

    使用async await  的线程同步问题如何来解决啊!

    谢谢!

    2014年8月20日 2:11

答案

  • 楼主 你好,

    可以把文件读写那一部分加上锁试试,

    	try
    	 {
    	   Object lockObj = new Object();
    	   lock(lockObj)
    	   {
    		//....
    	   }
    	 }
    	 catch (Exception ex)
    	 {
    		 Log("SaveLogFile Error", ex.Message);
    	 }
    谢谢!

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年8月20日 3:19
    版主