簡體   English   中英

多線程C#2.0混淆

[英]Multi-threading C# 2.0 confusion

我試圖弄清楚如何多線程應用程序。 我很難找到啟動線程的入口點。

我嘗試啟動的主題是: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)));

在.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();

這是一些示例代碼:

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
}

您不應該真正創建自己的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是字符串類型。 如果不是,只需將類型設置為正確的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM