简体   繁体   中英

Better .Net 4.0 Thread Control on User Tiggered Events

I have read many articles on .Net 4.0 threading. I have yet to understand how it will apply to my situation.

I have a .Net 4.0 application that is a chat bot for a game. It listens to users that can interface with the bot by typing an ! and the command. For Example: !online will run the code that will return the list that the users are online.

This is a plug in system, so when a command is detected, every plugin has a public void OnFirehandleCommand(object botArgs) available. Inside the code, I can determine if that specific command is for that plugin or not. Then the code is executed. The problem in the past is that the application will not process another command until the code for that command is finished. Some commands may take anywhere from a few seconds to 4 minutes to finish.

In order to remedy that, I attempted to use multithreading at the entry point where a command is requested by the user. I am using the following code:

 botArgs = new BotArgs {Bot = bot, Args = args};
                    var thread = new Thread(OnFirehandleCommand);
                    thread.Start(botArgs);

That is the extent of the threading that I use. This fires each time a command is given. However, this seems to be lacking any control at all, and as you see a new thread is generated each time a command is received. Is there a better way that I can use multithreading for this situation? Are there any examples for a situation like this?

Try tasks :

   var task = System.Threading.Tasks.Task.Factory.StartNew(
               () => OnFirehandleCommand(botArgs));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM