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

标签 c# web-services persistence object-persistence stateful

我现在有这样的东西:

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/

相关文章:

php - 如何编写在后台运行的异步 web 服务 php

ios - 核心数据设计 : better 1 model with 2 stores or 2 models and 2 stores?

c# - XmlReader内部文本问题

java - 了解 JBOSS 及其服务

c# - 如何模拟(或不模拟)IDbConnection 进行测试?

c# - ASMX 网络服务 : 'anonymous types' error

cocoa - 导入核心数据时建立关系?

spring - 没有命名 EntityManager 的持久性提供程序

c# - SetWindowsHookEx,键盘 Hook

c# - 如何在 AspNet.Membership.OpenAuth 中提供范围并从 facebook 获取额外数据?