How to Serialize an Object Containing a System.Threading.Thread? - c#

System.Runtime.Serialization.SerializationException:
Type 'System.Threading.Thread' in Assembly 'mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Is there a way around that? ive added the Serializable attribute to all of my class's, but i cant add attributes to things like that, can i? and if i can, is there a way to get around that issue altogether? because i dont want to always have to add [Serializable] to everything.
PS, in my project, im dynamically compiling C# code and including it in my application.
edit one: Because of the nature of my application, everything, all events, etc, is managed my separate threads.. I cannot get away from that fact, because i need to be doing many tasks at the same time. Is there a way to get around that fact?

One option would be to mark the thread object (and anything else you don't want serialized) as [NonSerialized].
You can then use whatever information you've serialized to reconstruct the non serialized objects.

You can't serialize a thread, so your best bet would be to remove the dependency on Thread from any class that you need to serialize. Usually you want your serializable objects to be composed mainly of primitive fields, or references to other objects that are also serializable.

[NonSerializable] is mispelled it should be [NonSerialized]

Related

Problem decoding a byte array to an object in C# [duplicate]

I'm serializing some data like fields and custom class to create a binary data (byte array).
Then I want to Deserialize it back from binary data to fields and class.
But I get an exception. It would all work fine if these two methods would happen in same assembly - but its not.
I do Serialization in one assambly, and do the Deserialization in another one. And this is the excaption saying too:
Unable to find assembly 'MyAssamblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
NOTE 1: I have no issues with getting the fields back, only the classes causes them.
NOTE 2: I have this same class in both assemblies.
NOTE 2: I have this same class in both assemblies
No you don't. At least, not as far as the runtime is concerned. You have two different types that happen to have the same name. A type is defined by its assembly. Thus "SomeType in AssemblyA" is completely different to "SomeType in AssemblyB", even if they happen to have been compiled from the same source file.
BinaryFormatter works with type information, so this won't work. One option would be to move the type to a library dll that both the other projects reference - then it is only defined once, and it will be happy.
Another option is to work with a contract-based serializer (rather than a type-based serializer). This means that "classes that look similar enough" are fine, even if they are in different assemblies (and perhaps have different source, as long as it is "similar enough"). Examples of suitable serializers for this would include (plus a few others) XmlSerializer, DataContractSerializer (but not NetDataContractSerializer), JavaScriptSerializer, or protobuf-net if you want dense raw binary.
All the assemblies containing classes in the class hierarchy of the object you are deserializing must be present in the application in which you are performing this deserialization. They could be either explicitly referenced (if you need compile-time safety with those classes) or only placed in the bin folder of the application so that they could be resolved at runtime. If they are not explicitly referenced you will have to use reflection in order to read the values from the deserialized instance.

Best way to initialize unknown types with parameters?

I'm trying to genericize some of our code by being able to instantiate objects that inherit from a base class without knowing the types of those objects. So I want to just be able to drop a dll in a directory and be able to instantiate those objects.
I was looking into MEF, but I can't export the parameters because they're not defined in code (loaded from a database). So it doesn't look like MEF is the way to go.
Reflection works great, but that seems too fragile to rely on.
Is there something I'm missing that would allow me to do this with MEF, is there another framework that would allow me to do this better, or is reflection simply the answer here?
If you only would spawn instance form a dll (assembly) on which you don't know anything could try do something like that :
_binaryData = File.ReadAllBytes(_path);
temporary = Assembly.Load(_binaryData);
foreach (Type type in temporary.GetTypes().Where(x => typeof(IBase) ).IsAssignableFrom(x))
var istance = (IBase) FormatterServices.GetUninitializedObject(x)
I do not recomend to do that, i suggest another aproach, store auxiliary information on that dll before load it or use attribute on type of your dll to help furhter analisis (and then loading).

Handling object deserialisation after changing namespace

I'm wondering is there any way to handle deserialisation after changing a classes, namespace?
At the moment I'm having to do an edit replace on the text value of the XML replacing old namespace with new namespace.
Is there a better way to do this?
Always a tricky one. Unless you can guarantee that the class won't change, then it's probably best to find another approach to serializing.
However, to answer the question, you could have a Version property of the class (or put it in a base class if you have many). You'll need to remember to increment this whenever you change the class.
Then you could have a series of "migrations", which would know how to transform the XML from one version to the next. When you want to deserialize, first load the file as XML, apply the migrations in turn (as there may have been several changes since the file was created), and then deserialize the now transformed XML.

Add new property to a class at runtime using reflection

I have some serialized data (using BinaryFormatter), and wanting to deserialise it. However the deserialise method failed since the current assembly does not have the deleted field. I want to be able to reconstruct earlier assembly at run-time in order to deserialise the data. Appreciated any pointer. Thanks.
the technique is called versiontolerant serialization
see http://msdn.microsoft.com/en-us/library/ms229752.aspx

Any way to "save state" in a C# game?

It's ok if the answer to this is "it's impossible." I won't be upset. But I'm wondering, in making a game using C#, if there's any way to mimic the functionality of the "save state" feature of console emulators. From what I understand, emulators have it somewhat easy, they just dump the entire contents of the virtualized memory, instruction pointers and all. So they can resume exactly the same way, in the exact same spot in the game code as before. I know I won't be able to resume from the same line of code, but is there any way I can maintain the entire state of the game without manually saving every single variable? I'd like a way that doesn't need to be extended or modified every single time I add something to my game.
I'm guessing that if there is any possible way to do this, it would use a p/invoke...
Well, in C# you can do the same, in principle. It's called serialization. Agreed, it's not the exact same thing as a memory dump but comes close enough.
To mark a class as serializable just add the Serializable attribute to it:
[Serializable]
class GameState
Additional information regarding classes that might change:
If new members are added to a serializable class, they can be tagged with the OptionalField attribute to allow previous versions of the object to be deserialized without error. This attribute affects only deserialization, and prevents the runtime from throwing an exception if a member is missing from the serialized stream. A member can also be marked with the NonSerialized attribute to indicate that it should not be serialized. This will allow the details of those members to be kept secret.
To modify the default deserialization (for example, to automatically initialize a member marked NonSerialized), the class must implement the IDeserializationCallback interface and define the IDeserializationCallback.OnDeserialization method.
Objects may be serialized in binary format for deserialization by other .NET applications. The framework also provides the SoapFormatter and XmlSerializer objects to support serialization in human-readable, cross-platform XML.
—Wikipedia: Serialization, .NET Framework
If you make every single one of your "state" classes Serializable then you can literally serialize the objects to a file. You can then load them all up again from this file when you need to resume.
See ISerializable
I agree with the other posters that making your game state classes Serializable is probably the way you want to go. Others have covered basic serialization; for a high end alternative you could look into NHibernate which will persist objects to a database. You can find some good info on NHibernate at these links:
http://www.codeproject.com/KB/database/Nhibernate_Made_Simple.aspx
http://nhibernate.info/doc/burrow/faq

Categories

Resources