首页 > 解决方案 > Process.Start,从 WebMethod 读取进度?

问题描述

我正在通过以下方式从 ASP.NET webform 启动控制台应用程序,从 Button 控件的 Click 事件处理程序调用:

Process p = new Process();
p.StartInfo.FileName = @"C:\HiImAConsoleApplication.exe";

// Set UseShellExecute to false for redirection.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.Arguments = "-u " + url + " -p BLAH";
p.StartInfo.CreateNoWindow = false;

// Set our event handler to asynchronously read the sort output.
p.OutputDataReceived += OutputReceived;

// Start the process.
p.Start();

// Start the asynchronous read of the sort output stream.
p.BeginOutputReadLine();
p.WaitForExit();

这很好用,我正在使用 OutputDataReceived 事件处理程序通过将接收到的消息添加到全局定义的字符串集合来毫无问题地读取控制台应用程序的输出,然后在计时器上我从 WebMethod 获取新消息。

protected static void OutputReceived(object sender, DataReceivedEventArgs e)
            {
                if (e.Data != null)
                {
                        messages.Add(myData);
                }
                if (messages.Count > 20)
                {
                    messages.Clear();
                }
            }

然后通过 WebMethod 检查消息:

 public static List<string> messages = new List<string>();

    [WebMethod]
    public static string[] CheckForNewMessages()
    {
        List<string> tempCollection = new List<string>();
        if (messages.ToArray().Length > 0)
        {
            foreach (string str in messages.ToArray())
            {
                    tempCollection.Add(str);
            }
        }

        return tempCollection.ToArray();
    }

这种方法的问题是,如果我有多个用户尝试使用该应用程序,他们显然会相互共享消息,这不是很好。我想知道是否有更好的方法可以让我更准确地支持多个用户。

TIA 专家!

标签: c#asp.net

解决方案


您可以使用字典并将用户的 Cookie 与可以阅读的消息连接起来。

public static Dictionary<string, string> messages = new Dictionary<string, string>();

关键,必须是用户cookie。

但这不是一个没有错误的解决方案。

错误号 1,在回收池时会丢失数据。
错误号 2,在您的网站的任何更新/编译中,您都会丢失您的数据。
错误 3,当您有多个池(网络花园)时,每个池都有其静态数据,因此同一用户可能会丢失/永远看不到他们的数据。

正确的方法是使用数据库,或者一些文件将它们写下来 - 并将消息与用户 cookie / 用户 ID 连接起来

ASP.NET 静态变量的生命周期


推荐阅读