2

我试图弄清楚如何对应用程序进行多线程处理。我被困在试图找到启动线程的入口点。

我试图启动的线程是:plugin.FireOnCommand(this, newArgs);

...
PluginBase plugin = Plugins.GetPlugin(Commands.GetInternalName(command));
plugin.FireOnCommand(this, newArgs);
...

FireOnCommand 方法是:

 public void FireOnCommand(BotShell bot, CommandArgs args)

我在使用 ParameterizedThreadStart 或 ThreadStart 时没有任何运气,我似乎无法获得正确的语法。

编辑:都试过了

Thread newThread = 
  new Thread(new ParameterizedThreadStart(plugin.FireOnCommand(this, newArgs))); 

Thread newThread = 
  new Thread(new ThreadStart(plugin.FireOnCommand(this, newArgs)));
4

3 回答 3

6

在 .NET 2 中,您需要为此创建一个具有自定义类型的方法。例如,您可以这样做:

internal class StartPlugin
{
    private BotShell bot;
    private CommandArgs args;
    private PluginBase plugin;

    public StartPlugin(PluginBase plugin, BotShell bot, CommandArgs args)
    {
       this.plugin = plugin;
       this.bot = bot;
       this.args = args;
    }

    public void Start()
    {
        plugin.FireOnCommand(bot, args);
    }
}

然后你可以这样做:

StartPlugin starter = new StartPlugin(plugin, this, newArgs);

Thread thread = new Thread(new ThreadStart(starter.Start));
thread.Start();
于 2013-05-21T22:40:10.190 回答
2

这是一些示例代码:

class BotArgs
{
    public BotShell Bot;
    public CommandArgs Args;
}

public void FireOnCommand(BotShell bot, CommandArgs args)
{
    var botArgs = new BotArgs {
        Bot = bot,
        Args = args
    };
    var thread = new Thread (handleCommand);
    thread.Start (botArgs);
}

void handleCommand (BotArgs botArgs)
{
    var botShell = botArgs.Bot;
    var commandArgs = botArgs.Args;
    //Here goes all the work
}
于 2013-05-21T22:36:18.470 回答
2

除非您计划与它交互,特别是与它所代表的线程交互,否则您不应该真正创建自己的 Thread 对象。对于交互,我的意思是停止它、重新启动它、中止它、暂停它或类似的事情。如果你只有一个你想要异步的操作,你应该去 ThreadPool 代替。试试这个:

private class FireOnCommandContext
{
    private string command;
    private BotShell bot;
    private CommandArgs args;

    public FireOnCommandContext(string command, BotShell bot, CommandArgs args)
    {
        this.command = command;
        this.bot = bot;
        this.args = args;
    }

    public string Command { get { return command; } }
    public BotShell Bot { get { return bot; } }
    public CommandArgs Args { get { return args; } }
}

private void FireOnCommandProc(object context)
{
    FireOnCommandContext fireOnCommandContext = (FireOnCommandContext)context;
    PluginBase plugin = Plugins.GetPlugin(Commands.GetInternalName(fireOnCommandContext.Command));
    plugin.FireOnCommand(fireOnCommandContext.Bot, fireOnCommandContext.Args);
}

...
FireOnCommandContext context = new FireOnCommandContext(command, this, newArgs);
ThreadPool.QueueUserWorkItem(FireOnCommandProc, context);

请注意,这将在单独的线程中完成工作,但一旦完成或任何事情,它就不会通知您。

另请注意,我command是字符串类型的。如果不是,只需将类型设置为正确的类型。

于 2013-05-21T22:40:35.633 回答