多线程C#2.0混淆

时间:2013-05-21 22:29:44

标签: c# multithreading

我试图找出如何多线程应用程序。我很难找到启动线程的入口点。

我尝试启动的主题是: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)));

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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
}

答案 2 :(得分: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是字符串类型。如果不是,只需将类型设置为正确的类型。