UpdateAsObservable() vs EveryUpdate() in UniRx? - c#

What's the different between:
UpdateAsObservable()
EveryUpdate()
in UniRx?
Are they the same?

Observable.EveryUpdate is defined as a static method, so it can be called from a place other than MonoBehaviour. Internally, the execution timing of CoreThreadDispatcher's corruption is notified.
For your reference, you need to be careful when using the IDisposable of the subscribers correctly (you will need to paste AddTo etc.)
ObservableUpdateTrigger is defined in the UniRx.Triggers namespace.
If you leave UniRx.Triggers outside of Using, you can call UpdateAsObservable () directly.
The entity is the ObservableUpdateTrigger
AddComponent is automatically added to the call at the time of the call (you do not have to worry about the presence of the trigger when you actually use it)
ObservableMonoBehaviour and internal structure are the same

Related

Creating objects at runtime

I'm working on an Unity3D application that basically fetches data from a server and attempts to create objects at runtime. When I'm trying to create this objects, via a constructor on some classes I have defined, I get the following error:
get_name can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function
I can't move this to either Awake or Start since I need some feedback from my GUI (user credentials) before I run the mentioned code.
Any ideas/suggestions?
You can't create objects in your constructor or you will get that error. In fact, you should eschew constructors in general with Unity and favour Awake/Start/etc.
I don't know what you're doing, but there's no reason why you can't Instantiate() the object somewhere in your code, set it up properly on the next lines of code, and then let it's Awake()/Start() take place after that, letting it be fully initialized.
I was able to make it work. Here's a summary of what I did:
Made the class instantiating the classes at run-time, referred as Creator, extend ScriptableObject. This allows to start the Creator class on demand using CreateInstance.
Change the Creator class methods, variables and the class itself to static.
When needed intantiate the Creatorclass via CreateInstance.
Make sure to call the methods that do the class instantiating from Start, Awake or Update as appropriate. In my case it was Update.

Return directly to caller of caller and restore state on next call

I'm building a plugin to a system. My plugin's update() method is called occasionally by the system.
In my plugin's update() method, I'm modifying the systems state, however the system state isn't updated until the system has had a chance to do so (this happens between invocations of the update method).
So whenever I do a system updating method I'll have to return all the way out of the update(), for it to return, and re-enter, and then I'll have to try to get back to where I was. I've been considering a smarter way to do this, namely by saving call frame, and such. And then loading that call-frame on return.
But instead of starting to implement this on my own, I was considering whether there was already a way to do this. The plugin I'm writing is in Lua, via the NLua library for C#.
I'm able to access the C# environment, if needed!
I have an idea, that I need something like a continuation?
Example of what I'd love to have;
update() --> ... --> helper_function() --> system_state_modifier()
// System state modifier changes system state, saves the current stack/registers,
// whatever else is needed, and returns directly to update()'s caller
// On the next call to update, the previous stack/registers and such
// is restored, and continued.
I was indeed looking for coroutines, they seem to do exactly what I want.
I ended up wrapping my update() can in a method to run the actual update function as a coroutine, and wrapping all my system state changing methods, with coroutine.yield()
Although the coroutine route is quite nice, another option might be, depending on constraints (like if you can pass obj to script) for the stack & registers to be put in a struct that is given as part of call:
struct StackAndRegisters { ... }
StackAndRegisters sar; // outside update loop
// then at every call:
update(sar) -> -> ... --> helper_function(sar) --> system_state_modifier(sar)
// system_state_modifier modifies sar

How to avoid passing a context reference among classes

Dynamics CRM 2011 on premise. (But this problem exists in many situations away from Dynamics CRM.)
CRM plugins have an entry point:
void IPlugin.Execute (IServiceProvider serviceProvider)
(http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.iplugin.execute.aspx)
serviceProvider is a reference to the plugin execution context. Anything useful that a plugin does requires accessing serviceProvider, or a member of it.
Some plugins are large and complex and contain several classes. For example, I'm working on a plugin that has a class which is instantiated multiple times. This class needs to use serviceProvider.
One way to get access to serviceProvider from all the classes that need it would be to add a property to all those classes and then to set that property. Or to add properties for the parts of serviceProvider that each class needs. Either of these approaches would result in lots of duplicate code.
Another approach would be to have a global variable in the scope of the thread. However, according to http://msdn.microsoft.com/en-us/library/cc151102.aspx one "should not use global class variables in plug-ins."
So what is the best way to have access to serviceProvider without passing it around everywhere?
P.S. If an example helps, serviceProvider provides access to a logging object. I want almost every class to log. I don't want to pass a reference to the logging object to every class.
That's not quite what the warning in the documentation is getting at. The IServiceProvider isn't a global variable in this context; it's a method parameter, and so each invocation of Execute gets its own provider.
For improved performance, Microsoft Dynamics CRM caches plug-in instances. The plug-in's Execute method should be written to be stateless because the constructor is not called for every invocation of the plug-in. In addition, multiple threads could be running the plug-in at the same time. All per invocation state information is stored in the context. This means that you should not use global class variables in plug-ins [Emphasis mine].
There's nothing wrong with passing objects from the context to helper classes which need them. The warning advises against storing something in a field ("class variable") on the plugin class itself, which may affect a subsequent call to Execute on the same instance, or cause concurrency problems if Execute is called by multiple threads on the same instance simultaneously.
Of course, this "globalness" has to be considered transitively. If you store anything in either the plugin class or in a helper class in any way that multiple calls to Execute can access (using fields on the plugin class or statics on either plugin or helper classes, for example), you leave yourself open to the same problem.
As a separate consideration, I would write the helper classes involved to accept types as specific to their function as possible - down to the level of individual entities - rather than the entire IServiceProvider. It's much easier to test a class which needs only an EntityReference than one which needs to have an entire IServiceProvider and IPluginExecutionContext mocked up.
On global variables vs injecting values required by classes
You're right, this is something that comes up everywhere in object-oriented code. Take a look at these two implementations:
public class CustomEntityFrubber
{
public CustomEntityFrubber(IOrganizationService service, Guid entityIdToFrub)
{
this.service = service;
this.entityId = entityIdToFrub;
}
public void FrubTheEntity()
{
// Do something with service and entityId.
}
private readonly IOrganizationService service;
private readonly Guid entityId;
}
// Initialised by the plugin's Execute method.
public static class GlobalPluginParameters
{
public static IOrganizationService Service
{
get { return service; }
set { service = value; }
}
public static Guid EntityIdToFrub
{
get { return entityId; }
set { entityId = value; }
}
[ThreadStatic]
private static IOrganizationService service;
[ThreadStatic]
private static Guid entityId;
}
public class CustomEntityFrubber
{
public FrubTheEntity()
{
// Do something with the members on GlobalPluginParameters.
}
}
So assume you've implemented something like the second approach, and now you have a bunch of classes using GlobalPluginParameters. Everything is going fine until you discover that one of them is occasionally failing because it needs an instance of IOrganizationService obtained by calling CreateOrganizationService(null), so it accesses CRM as the system user rather than the calling user (who doesn't always have the required privileges).
Fixing the second approach requires you to add another field to your growing list of global variables, remembering to make it ThreadStatic to avoid concurrency problems, then changing the code of CustomEntityFrubber to use the new SystemService property. You have tight coupling between all these classes.
Not only that, all these global variables hang around between plugin invocations. If your code has a bug that somehow bypasses the assignment of GlobalPluginParameters.EntityIdToFrub, suddenly your plugin is inexplicably operating on data that wasn't passed to it by the current call to Execute.
It's also not obvious exactly which of these global variables the CustomEntityFrubber requires, unless you read its code. Multiply that by however many helper classes you have, and maintaining this code starts to become a headache. "Now, does this object need me to have set Guid1 or Guid2 before I call it?" On top of that, the class itself can't be sure that some other code won't go and change the values of global variables it was relying on.
If you used the first approach, you simply pass in a different value to the CustomEntityFrubber constructor, with no further code changes needed. Furthermore, there's no stale data hanging around. The constructor makes it obvious which dependencies the class has, and once it has them, it can be sure that they don't change except in ways they were designed for.
As you say, you shouldn't put a member variable on the plugin since instances are cached and reused between requests by the plugin pipeline.
The approach I take is to create a class that perform the task you need and pass a modified LocalPluginContext (making it a public class) provided by the Developer Toolkit (http://msdn.microsoft.com/en-us/library/hh372957.aspx) on the constructor. Your class then can store the instance for the purposes of executing it's work just in the same way you would with any other piece of code. You are essentially de-coupling from the restrictions imposed by the Plugin framework. This approach also makes it easier to unit test since you only need to provide the execution context to your class rather than mocking the entire plugin pipeline.
It's worth noting that there is a bug in the automatically generated Plugin.cs class in the Developer Toolkit where it doesn't set the ServiceProvider property - At the end of the constructor of the LocalPluginContext add the line:
this.ServiceProvider = serviceProvider;
I have seen some implementations of an IoC approach in Plugins - but IMHO it makes the plugin code way too complex. I'd recommend making your plugins lean and simple to avoid threading/performance issues.
There are multiple things I would worry about in this design request (not that it's bad, just that one should be aware of, and anticipate).
IOrganizationService is not multi-thread safe. I'm assuming that other aspects of the IServiceProvider are not as well.
Testing things at an IServiceProvider level is much more complicated due to the additional properties that have to be mocked
You'd need a method for handle logging if you ever decided to call logic that is currently in your plugin, outside of the plugin (e.g. a command line service).
If you don't want to be passing the object around everywhere, the simple solution is to create a static property on some class that you can set it upon plugin execution, and then access from anywhere.
Of course now you have to handle issue #1 from above, so it'd have to be a singleton manager of some sort, that would probably use the current thread's id to set and retrieve the value for that thread. That way if the plugin is fired twice, you could retrieve the correct context based on your currently executing thread. (Edit Rather than some funky thread id lookup dictionary, #shambulator's ThreadStatic property should work)
For issue #2, I wouldn't be storing the IServiceProvider as is, but split up it's different properties (e.g. IPluginExecutionContext, IOrganizationService, etc)
For issue #3, it might make sense to store an action or a function in your manager rather than the object values themselves. For example, if rather than storing the IPluginExecutionContext, store a func that accepts a string to log and uses the IPlurginExeuctionContext to log. This allows other code to setup it's own logging, without being dependent on executing from within a plugin.
I haven't made any of these plugins myself, but I would treat the IServiceProvider like an I/O device.
Get the data you need from it and convert that data to format that suits your plugin. Use the transformed data to set up the other classes. Get the the output from the other classes and then translate back to terms the IServiceProvider can understand and use.
Your input and output are dependent on the IServiceProvider, but the processing doesn't have to be.
From Eduardo Avaria at http://social.microsoft.com/Forums/en-US/f433fafa-aff7-493d-8ff7-5868c09a9a9b/how-to-avoid-passing-a-context-reference-among-classes
Well, as someone at SO already told you, the global variables restriction is there cause the plugin won't instantiate again if it's called within the same context (the object context and probably other environmental conditions), so any custom global variable would be shared between that instances, but since the context will be the same, there's no problem in assigning it to a global variable if you want to share it between a lot of classes.
Anyways, I'd rather pass the context on the constructors and share it have a little more control over it, but that's just me.

Static values vs passing parameters

I have a situation where I have to pass a List<> across 2-3 independent classes up and down the class. Right now I'm mostly passing the list using parameter so all 3 classes gets the list. Should I use a static list instead of passing List all over the classes to simplify the code like Class23.ListObjects.Add() and then release the static values once the operation is done so the next operation starts with an empty List. Right now it feels like the parameters are getting a lot and I'm getting confused if the list has the right values, forgetting to pass the list to the next class, etc. What do you think?
I would suggest you create a new class that represents the combined operation performed by the various classes (a "context" class, if you will). Values needed to perform the operation can be held as instance variables in that context, along with instances of the classes used in performing the work.
That way, you avoid passing stuff around (as code evolves, this can get somewhat ugly) while avoiding a "global" variable. Data is in exactly the scope it needs to be, and is disposed when the overall operation is complete.
In Coding practices, it is bad to have static or Global variables and passing through parameters is considered good.
If you use a static parameter, you run the risk of getting corrupted data if those functions are used in multiple places in your code, especially if threading is involved.
For instance, suppose Class A needs to use your functions that act on your static list. Before those functions are completed, Class B tries to use them as well, causing the list to get data from both calls, since the same static list is used in both cases.

Static Method Confusion

I am working with Asp.NET and I have a class named PathFinder which has methods like StyleBarPath(string BrandId,string ProductId) which returns for example a combination of path including brandId and productId and also there are such methods in the same class.
What I am thinking to make them static methods to invoke them easily in every where by saying PathFinder.StylePath("1","2"); to use the returned values inside a user control.
But since I am working too much these days, what I know is getting complicated for some reasons. Anyways, here is my question :
Since I am using inline coding on a lot of places like <a href='<%=PathFinder.StylePath("1","2")%>'></a>, I don't want to create a lot of instances by doing this <a href='<%=new PathFinder().StylePath("1","2")%>'></a> by declaring the methods not-static.
But I am afraid of changing the methods returns values because defining the methods static. I mean when a client calls this method, it wouldn't affect the other clients who invoke the same method at the same time?
They would have different call stacks right?
Lets say :
client one invokes the method with these parameters -- {brandId:2,productId:3}
client tow invokes the method with these parameters -- {brandId:3,productId:4}
This actions happens near the same time when the server processing their requests. What I want to learn is whether the invocations affect each others and change the returning values of each other since they are defined static.
Thanks for reading so far and being a helper :)
I just don't want the clients see path/1/2/ while they are waiting for path/2/3/
Some Notes about the question :
Is it the same for static fields?
You can call a static method safely from multiple threads simultaneously and at separate times given the following:
The static method does not access variables outside of itself, or those variables are also thread safe.
The static method does not create side effects which are not thread safe.
If your method is what it looks like it is, you're simply taking some inputs adjusting them and returning the result without accessing anything outside of the function. That would be completely safe.
Static fields are not the same as methods at all. It is one copy of a variable. Any changes to that static field will affect everything else that uses it.
In C#, static means (in layman's terms) there is one copy.
If you provide arguments to the method, and you return a value based on those parameters only, then you will be perfectly safe.
The only time you might run into problems is if your static method uses any static variables to store data between calls, since that could make call-1 change the value of call-2.
From the example you gave, you are safe.
As for your question about static fields, each caller can see the same static fields, since those are shared between instances. Keep that in mind while programming!
This should answer most of you questions
http://odetocode.com/Articles/313.aspx
As I understand it, static methods are thread safe, but not static properties

Categories

Resources