zoukankan      html  css  js  c++  java
  • How to Execute a Command via C#

    Introduction

    It is normal practice to open the Windows command prompt and execute commands. The command when executed shows the result onto the screen. There are many commands that we execute daily such as dir, find, etc. A situation may arise when you want to execute a (shell) command from the C# application.

    Don't worry!!! Here is the code to do so…

    Using the Code

    The code given below creates a process i.e. a command process and then invokes the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further reference. The command execution can happen in two ways, synchronously and asynchronously. In the asynchronous command execution, we just invoke the command execution using a thread that runs independently. The code has enough comments, hence making it self-explanatory.

    Below is the code to execute the command synchronously:

    Below is the code to execute the command asynchronously:

    If we observe carefully, the asynchronous execution of the command actually invokes the synchronous command execution method using a thread. The thread runs in the background making the command execution asynchronous in nature.

    In the above execution sample, we find that there are two result sets of the command "dir". The first one appears immediately after the command and the second appears after the "Done!" statement. In this case, the first one is the synchronous execution of the command, which happens immediately and the second is the asynchronous execution of the "dir" command.

  • 相关阅读:
    可能有点用的东西
    专题整理
    模拟赛x+1
    【原】如何利用 events 提升 k8s 集群可观察性
    【原】k8s ingress-nginx 针对指定 User-Agent 爬虫进行限速
    装饰者模式-动态的包装原有对象的行为
    观察者模式-将消息通知给观察者
    策略模式-定义一个算法族
    工厂模式-将对象的创建封装起来
    单例模式的五种实现方式及优缺点
  • 原文地址:https://www.cnblogs.com/Blackeye286/p/3210810.html
Copyright © 2011-2022 走看看