C#: Вызовите метод с [Типом].InvokeMember () в отдельном Потоке

Благодаря @WillKeeling я понял, что в моем методе save () есть ссылка на Finding.q_id, которую я забыл обновить после внесения изменений в FK. PK внешней таблицы - qkb_id, поэтому я изменил ссылку на Finding.q_id.qkb_id и смог сохранить модель.

7
задан Rex M 26 April 2009 в 16:53
поделиться

2 ответа

Если Вы знаете, что все Ваше динамично загруженное Выполнение реализации типов, могли просто потребовать, чтобы они все реализовали IRunable и избавились от отражательной части?

Type t = robotList[i];
IRunable o = Activator.CreateInstance(t) as IRunable;
if (o != null)
{
    o.Run(); //do this in another thread of course, see below
}

В противном случае это будет работать:

for (int i = 0; i < robotList.Count; i++)
{
    Type t = robotList[i];
    object o = Activator.CreateInstance(t);
    Thread thread = new Thread(delegate()
    {
        t.InvokeMember("Run", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, null);
    });
    thread.Start();
}
19
ответ дан 6 December 2019 в 08:46
поделиться

Взгляните на этот образец для одного способа сделать его:

using System;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;

namespace Obfuscation
{
    public class Program
    {
        static Type[] robotArray = new Type[] { typeof(Program) };
        static List<Type> robotList = new List<Type>(robotArray);

        internal void Run()
        {
            Console.WriteLine("Do stuff here");
        }

        internal static void RunInstance(object threadParam)
        {
            Type t = (Type)threadParam;
            object o = Activator.CreateInstance((Type)t);
            t.InvokeMember("Run", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, o, null);
        }

        public static void Main(string[] args)
        {
            for (int i = 0; i < robotList.Count; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(RunInstance), robotList[i]);
            }
        }
    }
}
2
ответ дан 6 December 2019 в 08:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: