我有以下方法将 UnixTimestamp 格式化为格式化的日期和时间:
public string ConvertDateTimeToDeviceShortDateFormat(double unixTimestamp)
{
using (var dateInNsDate = NSDate.FromTimeIntervalSince1970(unixTimestamp))
{
using (var formatter = new NSDateFormatter())
{
formatter.TimeStyle = NSDateFormatterStyle.None;
formatter.DateStyle = NSDateFormatterStyle.Short;
formatter.Locale = NSLocale.CurrentLocale;
return formatter.ToString(dateInNsDate);
}
}
}
在我的 Xamarin.Forms 应用程序中每秒都会调用此方法,有时在调用此方法时会抛出 ObjectDisposeException。
Xamarin Exception Stack:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Foundation.NSDate'.
at ObjCRuntime.ThrowHelper.ThrowObjectDisposedException (System.Object o) <0x101ca8be0 + 0x00038> in <153620f857f54f9c9ab1e7a1e6853772#0f6f385f46b536c4b979ed569af516e5>:0
at ObjCRuntime.NativeObjectExtensions.GetNonNullHandle (ObjCRuntime.INativeObject self, System.String argumentName) <0x101ca5d70 + 0x00077> in <153620f857f54f9c9ab1e7a1e6853772#0f6f385f46b536c4b979ed569af516e5>:0
at Foundation.NSDateFormatter.ToString (Foundation.NSDate date) <0x101c1f920 + 0x00027> in <153620f857f54f9c9ab1e7a1e6853772#0f6f385f46b536c4b979ed569af516e5>:0
每次调用时处理 NSDate 是否存在问题?
显然,代码不是线程安全的。我通过强制多线程调用重现了该错误。
我最终使用锁来确保独占访问,这解决了我的问题。