gpt4 book ai didi

c# - 是否可以在 C# 中创建有状态 Web 服务?

转载 作者:太空狗 更新时间:2023-10-29 21:30:47 25 4
gpt4 key购买 nike

我现在有这样的东西:

public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string Method1()
{
SomeObj so = SomeClass.GetSomeObj(); //this executes very long time, 50s and more
return so.Method1(); //this exetus in a moment
}

[WebMethod]
public string Method2()
{
SomeObj so = SomeClass.GetSomeObj(); //this executes very long time, 50s and more
return so.Method2(); //this exetus in a moment
}

...
}

是否可以制作有状态的 Web 服务,以便我可以重用 SomeObj so 并只调用同一对象上的方法?

因此,将使用此服务的客户端将首先调用将创建 so 对象并返回一些 ID 的 Web 方法。然后在后续调用中,Web 服务将根据 ID 重用相同的 so 对象。

编辑


这是我的实际代码:

[WebMethod]
public List<ProcInfo> GetProcessList(string domain, string machineName)
{
string userName = "...";
string password = "...";
TaskManager tm = new TaskManager(userName, password, domain, machineName);

return tm.GetRunningProcesses();
}

[WebMethod]
public bool KillProcess(string domain, string machineName, string processName)
{
string userName = "...";
string password = "...";
(new TaskManager(userName, password, domain, machineName);).KillProcess(processName);
}

最佳答案

有状态网络服务不可扩展,我不推荐它们。相反,您可以将昂贵操作的结果存储在 cache 中。 .此缓存可以通过自定义提供程序分发,以获得更好的可扩展性:

[WebMethod]
public string Method1()
{
SomeObj so = TryGetFromCacheOrStore<SomeObj>(() => SomeClass.GetSomeObj(), "so");
return so.Method1(); //this exetus in a moment
}

[WebMethod]
public string Method2()
{
SomeObj so = TryGetFromCacheOrStore<SomeObj>(() => SomeClass.GetSomeObj(), "so");
return so.Method2(); //this exetus in a moment
}

private T TryGetFromCacheOrStore<T>(Func<T> action, string id)
{
var cache = Context.Cache;
T result = (T)cache[id];
if (result == null)
{
result = action();
cache[id] = result;
}
return result;
}

关于c# - 是否可以在 C# 中创建有状态 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4117790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com