每秒检查数据库值,同时允许用户执行其他操作

时间:2013-09-23 21:07:46

标签: c# asp.net multithreading web-applications

我需要一个进程,每秒检查一次数据库中的值是否为true,这是由windows服务设置为true。

当值为true时更新图像。 但我需要的是,当值为false时,用户可以自由地在页面中执行其他活动。

我一直在寻找多线程通信,但我真的找不到满足我特定需求的东西。

感谢您的帮助

我在这里添加我的代码:

private static class QuickUpdateCompletedCheck
{
    #region BEGIN Declares

    private static ProcessStatus quickUpdateCompletedStatus;
    private static Thread quickUpdateThread;
    private static ISynchronizeInvoke quickUpdateCompletedSynch;
    private static bool updateCompleted;
    private static QuickUpdateInfo quickUpdateInfo = null;

    public delegate void UpdateCompletedStatusCheck(string Message, int status);

    #endregion END Declares
    #region BEGIN Initialization

    public QuickUpdateCompletedCheck(ISynchronizeInvoke syn, ProcessStatus notify, Guid userIdLoc, int activityIdLoc, int fileIdLoc, int spreadIdLoc)
    {
        quickUpdateCompletedSynch = syn;
        quickUpdateCompletedStatus = notify;
        quickUpdateInfo = new QuickUpdateInfo(activityIdLoc, fileIdLoc, spreadIdLoc, userIdLoc);
    }

    #endregion END Initialization
    #region BEGIN Methods

    public void StartProcess()
    {
        quickUpdateThread = new System.Threading.Thread(new ParameterizedThreadStart(UpdateStatus));
        //set the thread to run in the background
        quickUpdateThread.IsBackground = true;
        //name our thread (optional)
        quickUpdateThread.Name = "Add List Items Thread";
        //start our thread
        quickUpdateThread.Start();
    }

    private static void UpdateStatus(object data)
    {
        QuickUpdateInfo quickUpdateInfo = (QuickUpdateInfo)data;

        object[] dataInfo = new object[4];

        dataInfo[0] = quickUpdateInfo.ActivityId;
        dataInfo[1] = quickUpdateInfo.FileId;
        dataInfo[2] = quickUpdateInfo.SpreadId;
        dataInfo[3] = quickUpdateInfo.UserId;

        quickUpdateCompletedSynch.Invoke(QuickUpdateCompletedataInfo); //Here I have an error need a delegate method in first parameter. i suppose is the QuickUpdateComplete method at the end of this description
    }

    #endregion END Methods
}

public class QuickUpdateInfo
{
    private int activityId;
    private int fileId;
    private int spreadId;
    private Guid userId;

    public int ActivityId
    {
        get { return activityId; }
    }

    public int FileId
    {
        get { return fileId; }
    }

    public int SpreadId
    {
        get { return spreadId; }
    }

    public Guid UserId
    {
        get { return userId; }
    }

    public QuickUpdateInfo(int activityId, int fileId, int spreadId, Guid userId)
    {
        this.activityId = activityId;
        this.fileId = fileId;
        this.spreadId = spreadId;
        this.userId = userId;
    }
}

此方法在页面中最新更新的图像

public partial class SpreadCorrection : BasePage
{
        protected void UpdatePostBack_OnClick(object sender, EventArgs e)
    {
                //how to start Thread here
    }

    private static void QuickUpdateComplete(int activityId, int fileId, int spreadId)
    {
        if (value from database is true)
        {   
                    UpdateImage();
                    //how to stop Thread here
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用JavaScript的setInterval()函数和jQuery的.ajax()函数来调用服务器端的服务来检查值,如下所示:

function checkForDatabaseValue() {
    $.ajax({
        type: "POST",
        url: "YourPage.aspx/GetDatabaseValue",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function (data) {
            // Do something with data returned here
        },
        error: function (errorMessage) {
            // Do something with error message here
        },
        complete: function() {
            // Reset the timer to a minute here
            setTimeout(function() { 
                checkForDatabaseValue(); 
            }, 60000);
        }
    });
}

YourPage.aspx可以托管ASP.NET AJAX页面方法来执行自动编码为JSON数据的简单页面托管服务,如下所示:

[WebMethod]
public static string GetDatabaseValue()
{
    // Put database retrieval logic here
}

注意:您需要引用ASP.NET AJAX库才能使用Page Methods。上述setInterval.ajax()调用也适用于ASP.NET XML Web Services(.asmx)和WCF服务,但由于其简单性,我展示了ASP.NET AJAX Page Method方法。

答案 1 :(得分:1)

ASP.Net中有多种运行后台线程的方法。

以下是ASP.Net的一个简单示例 - Easy Background Tasks in ASP.NET

它将使用缓存在指定的时间间隔(当前为30秒)内调用您的代码。

void Application_Start(object sender, EventArgs e)
{
    AddTask("DoStuff", 30); // 30 seconds
}

private static CacheItemRemovedCallback OnCacheRemove;

private void AddTask(string name, int seconds)
{
    OnCacheRemove = CacheItemRemoved;

    HttpRuntime.Cache.Insert(name, seconds, null, 
        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
        CacheItemPriority.NotRemovable, OnCacheRemove);
}

public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
    // Checks if a value from database is true. 
    // If so, call to your method here ...

    AddTask(k, Convert.ToInt32(v));
}