I am trying to write a tweening class, and in order to do so I have a static Tweener.TweenTo method. In it, we start a thread in order to not hold up external operations. The method looks like this:
public static void TweenTo<T>(ref ITweenable<T> obj, T target, double ms)
{
new System.Threading.Thread(() => {
System.Threading.Thread.Sleep(5000)
obj.DoStuff(5,5) //throws exception because obj is a ref parameter
}).Start()
}
I understand that using the ref parameter in the lambda means that it may be a dangling reference, but I need to be able to use it in case the user tries to pass a value type or struct to the method. I have tried using parameterized thread start, but that coerces things to an object, which I cannot use (unboxing etc.). I have also tried using a wrapper class that holds a pointer to it, but this runs in to complications later down the line.
I would like a way of using this ref parameter in the thread, and ideally preserving its lifetime inside it.
Any help is appreciated :D
Edit: Olivier's answer close to what I need, but MyClass would be a struct in some cases, and it will duplicate whenever it can. This means that it would lose the reference and give values from the wrong instance.
Edit 2: example struct
public struct MyStruct : ITweenable<T> {
int x;
int y;
public MyStruct(int X) {
this.x=X;
}
public void DoStuff(int newX, int newY) {
this.x=newX;
this.y=newY;
}
}
public interface ITweenable<T> {
void DoStuff(int newX, int newY);
}
Edit 3: I haven't tested this so when I have I will give it as an answer - have tested now, doesn't work:
public static void TweenTo<T>(ITweenable<T> obj, T target, double ms)
{
Func<ITweenable<T>> getTween = ()=>{return obj;}
new System.Threading.Thread(() => {
System.Threading.Thread.Sleep(5000)
getTween().DoStuff(5,5);
}).Start()
}