C#MVC保持线程活动以便稍后恢复数据

时间:2017-11-14 03:06:12

标签: c# asp.net-mvc multithreading

我有一个特定的字符串(实际上是一个RSAParameter但我可以将它转换为字符串),我需要在MVC应用程序中保存“保存”而不实际保存它。考虑到MVC是如何工作的,我认为以我想要的方式执行此操作的唯一解决方案(如果有的话)是创建一个线程并使其保持活着并保存我需要的信息。当我再次询问这些信息或者经过一定的时间后,该线程就会死亡。

所以,我想到了以下

public string GetPublicString()
{
    string PublicString = "MyPublicString";
    string PrivateString = "MyPrivateString";
    Thread thread = new Thread(PrivateStringHolder);
    thread.Start(PrivateString);
    return PublicString;
}

public void PrivateStringHolder(object state)
{
    string PrivateString = (string)state;
    // Something that keeps this thread alive for 30 seconds
    // Something that keeps this thread alive until it's called
}

public GetPrivateString()
{
    // Something that retrieves the PrivateString inside PrivateStringHolder
}

我不知道我是否正确思考...之前从未使用过线程,所以我要求你的帮助。任何人都知道如何编写使我的线程保持活动30秒或直到从“GetPrivateString”方法调用它的方法,以及如何从“GetPrivateString”方法调用该函数来检索线程内的“PrivateString”?

我认为我可以使用ManualResetEvent,所以也许“......或者从GetPrivateString中调用它......”可以解决这个问题:

public string GetPublicString()
{
    string PublicString = "MyPublicString";
    string PrivateString = "MyPrivateString";
    Thread thread = new Thread(PrivateStringHolder);
    thread.Start(PrivateString);
    return PublicString;
}

ManualResetEvent mre = new ManualResetEvent();

public void PrivateStringHolder(object state)
{
    string PrivateString = (string)state;
    // Something that keeps this thread alive for 30 seconds
    mre.WaitOne();
}

public string GetPrivateString()
{
    // Something that retrieves the PrivateString inside PrivateStringHolder
    mre.Set();
    return PrivateString; // Assuming that I saved the private string in the PrivateString var
}

我会感激任何帮助。谢谢!

0 个答案:

没有答案