Process.Start,从WebMethod读取进度



我正在通过以下方式从ASP.NET Web窗体启动控制台应用程序,从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专家!

您可以使用Dictionary并将Cookie Of the User连接到可以读取的消息

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

密钥必须是用户cookie。

但这并不是一个没有bug的解决方案

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

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

ASP.NET静态变量的生存期

最新更新