我正在Xamarin学习Realm。
我正在尝试使用 ObjectMapper objectMapper = new ObjectMapper();
byte[] bytesToWrite = objectMapper.writeValueAsBytes(yourObject)
ObjectMetadata omd = new ObjectMetadata();
omd.setContentLength(bytesToWrite.length);
transferManager.upload(bucketName, filename, new ByteArrayInputStream(bytesToWrite), omd);
插入一些示例数据。我没有遇到任何问题,直到我在多个线程中调用相同的函数。领域文档说要在Thread
内执行插入操作,但我在Realm-Xamarin中看不到任何类似的方法。
这是代码。
executeTransactionAsync
主题类:
Thread thread1 = new Thread(() => TestThread.CountTo10("Thread 1"));
thread1.Start();
Thread thread2 = new Thread(() => TestThread.CountTo10("Thread 2"));
thread2.Start();
领域对象:
public class TestThread
{
public static Realm realm;
public static void CountTo10(string _threadName)
{
realm = Realm.GetInstance();
for (int i = 0; i < 5; i++)
{
realm.Write(() =>
{
RandomNumber random = new RandomNumber();
System.Console.WriteLine("Iteration: " + i.ToString() + " Random No: " + random.number.ToString() + " from " + _threadName);
realm.Manage(random);
});
Thread.Sleep(500);
}
}
}
答案 0 :(得分:2)
问题是您的realm
变量是static
,这最终会导致非法线程访问。只需删除static
,就可以了:
public class TestThread
{
public void CountTo10(string _threadName)
{
Realm realm = Realm.GetInstance();
for (int i = 0; i < 5; i++)
{
realm.Write(() =>
{
RandomNumber random = new RandomNumber();
System.Console.WriteLine("Iteration: " + i.ToString() + " Random No: " + random.number.ToString() + " from " + _threadName);
realm.Manage(random);
});
Thread.Sleep(500);
}
// no need to call `Realm.close()` in Realm-Xamarin, that closes ALL instances.
// Realm instance auto-closes after this line
}
}