Jan 17, 2012

[How to] Refresh UI in Threads (Delegate)

private delegate void Updater(Control ctrl);


private void Update(Control ctrl)
{
    if (this.InvokeRequired)
    {
        Updater u = new Updater(Update);
        this.Invoke(u, ctrl);
    }
    else
    {
        ctrl.Refresh();
    }
}


And call this method in threads
this.Update(this);

Jan 10, 2012

[How to] Change Task of Thread (Delegate)

using System.Threading;

Action task;

void task1() { }
void task2() { }
void task3() { }

void doTask(){
    while (true)
        task();
}

Thread thread = new Thread(doTask);
task = task1;
thread.Start();

Switch to task2
task = task2;


Switch to task3
task = task3;


And so on.

Jan 9, 2012

[How to] Function Array (Delegate)

using System;


case: void funcs(void)
Action[] func = {func1, func2, func3, ...};


case: void funcs(int)
Action<int> func = {func1, func2, func3, ...};


case: bool funcs(void)
Func<bool> func = {func1, func2, func3, ...};


Refer to all of the overloaded constructor of Action and Func.

[How to] Load Class From Assembly

using System.Reflection;

Assembly asm = Assembly.LoadFrom("file.dll");
Type type = asm.GetType("namespace.classpath");

object obj = Activator.CreateInstance(type);


Or
object obj = Activator.CreateInstance(type, new object[] {param1, param2, param3, ...});


Do any casting if needed.