用的UpdatePanel的AsyncTask? [英] AsyncTask with a Updatepanel?

查看:147
本文介绍了用的UpdatePanel的AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哟,我创建了一个WebProject如果测试它可以创建一个AsyncTask的更新进度:

Yo, i have created a WebProject to test if its possible to create a asyncTask to update a Progressbar:

public partial class AsyncTest : System.Web.UI.Page
{
    private String _taskprogress;
    private AsyncTaskDelegate _dlgt;
    protected delegate void AsyncTaskDelegate();

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public String GetAsyncTaskProgress()
    {
        return _taskprogress;
    }

    public IAsyncResult OnBegin(object sender, EventArgs e,
       AsyncCallback cb, object extraData)
    {
        _taskprogress = "AsyncTask started at: " + DateTime.Now + ". ";

        _dlgt = new AsyncTaskDelegate(ReadFile);
        IAsyncResult result = _dlgt.BeginInvoke(cb, extraData);

        return result;
    }

    public void ReadFile()
    {
        try
        {
            string Filename = @"D:\Material.txt";
            int filelength = TotalLines(Filename); //just reads the lines of the file

            ProgressBar1.Maximum = filelength;

            using (StreamReader reader = new StreamReader(Filename))
            {
                string line;
                int actualfileline = 1;
                while ((line = reader.ReadLine()) != null)
                {
                    string test = line;
                    ProgressBar1.Value = actualfileline;
                    actualfileline++;
                    //UpdatePanel1.Update(); <- Doesnt work
                    System.Threading.Thread.Sleep(5);
                }
            }
        }
        catch (Exception ex)
        {
            string exm = ex.Message.ToString();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        OnBegin(this, null, null, null);

    }
}

Aaaand我aspx- code:(我有一个ScriptManager肯定也)

Aaaand my aspx-code: (i have a scriptmanager for sure also)

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Button runat="server" ID="btnDoTask" Text="Do Task" OnClick="Button1_Click" />
        <br />
        <br />
        <eo:ProgressBar ID="ProgressBar1" runat="server" Width="250px" 
            BackgroundImage="00060301" BackgroundImageLeft="00060302" 
            BackgroundImageRight="00060303" ControlSkinID="None" IndicatorImage="00060304">
        </eo:ProgressBar
    </ContentTemplate>
</asp:UpdatePanel>

调用Updatepanel1.Update()不起作用,因为它说:

Calling the Updatepanel1.Update() doesnt work, because it says:

您只能调用Update-methoe bevor渲染

You can only call the Update-methoe bevor rendering

所以,我还能怎么更新呢?
我希望用户看到进度条的进展 - 因为我要实现code的大文件读取片。
林真正的新异步编程,所以林不知道是否有你需要的一切:/

So how else can i update it then ? I want the user to see the progress on the progressbar - because i want to implement a bigger file-reading piece of code. Im really new to async-programming, so im not sure if there is everything you need :/

编辑:

好吧,现在我在页面中创建一个Web服务:

Okay, now I created a Webservice in my page:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string GetProcess()
{
    if (actualfileline != null)
    {
        return actualfileline.ToString();
    }
    else
    {
        return "0";
    }
}

我想叫它槽我的按钮:

And i want to call it trough my Button:

<asp:Button runat="server" ID="btnDoTask" Text="Do Task" OnClick="Button1_Click" OnClientClick="StartJavaScriptProgress()" />

JavaScript的部分:

The javascript-part:

function StartJavaScriptProgress()
{
    var elm = document.getElementById("LabelProgress");
    elm.innerText = "Currently Working ...";
    setTimeout(WebService(), 1000);
};

function WebService() {
    $.ajax(
    {
        type: "POST",
        url: "AsyncTest.aspx/GetProcess",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            alert("Worked");
            var elm = document.getElementById("ProgressBar1");
            elm.value = response.d; 
        },
        error: function (jqXHR, textStatus, errorThrown) {

            alert("Error starting process");
        }
    })
};

但它不工作...

But it doesnt work ...

推荐答案

在另一个线程读取文件同步不会提高你的web应用程序的性能,检查的这个,获取更多详情。相反,你应该使用像 ReadLineAsync 自然异步API,并启用与 RegisterAsyncTask HTTP请求的异步完成,像这样的:

Reading a file synchronously on another thread will not improve the performance of your web app, check this for more details. Instead, you should be using a naturally asynchronous API like ReadLineAsync, and enable asynchronous completion of the HTTP request with RegisterAsyncTask, like this:

// Make sure to enable asynchronous request processing:
// <%@ Page Async="true" ... %>

public partial class AsyncTest : System.Web.UI.Page
{
    private String _taskprogress;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        RegisterAsyncTask(new PageAsyncTask(ReadFileAsync));
    }

    public async Task ReadFileAsync()
    {
        try
        {
            string Filename = @"D:\Material.txt";
            int filelength = TotalLines(Filename); //just reads the lines of the file

            ProgressBar1.Maximum = filelength;

            using (StreamReader reader = new StreamReader(Filename))
            {
                string line;
                int actualfileline = 1;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    string test = line;
                    ProgressBar1.Value = actualfileline;
                    actualfileline++;
                    //UpdatePanel1.Update(); <- Doesnt work
                    System.Threading.Thread.Sleep(5);
                }
            }
        }
        catch (Exception ex)
        {
            string exm = ex.Message.ToString();
        }
    }
}

请注意,这仍然将不会更新在客户端页面的进度UI。这样做是制作的电流的HTTP请求来完成的的异步服务器的一面。该浏览器将仍然在等待它。这将提高你的web应用程序的可扩展性,但​​在客户端的网页将被渲染,只有当 ReadFileAsync 已全面完成。

Note, this still won't update the progress UI in the client side page. What this does is making the current HTTP request to finish asynchronously on the server side. The browser will still be waiting for it. This improves the scalability of your web app, but the web page on the client side will be rendered only when ReadFileAsync has been fully completed.

如果您要提供在客户端的最新进展,你应该使用AJAX和通过XHR请求启动上述漫长的过程,还是一个隐藏的框架内。然后,您将能够跟踪其进度与辅助XHR请求,并更新UI。在 ReadFileAsync ,你需要不断的进展信息会话变量,例如内会话[actualfileline] = actualfileline 。你会访问会话[actualfileline] 从二级XHR请求。

If you want to provide the progress updates on the client side, you should use AJAX and start the above lengthy process via XHR request, or inside a hidden frame. You would then be able to track its progress with a secondary XHR request and update the UI. Inside ReadFileAsync, you'd need to keep the progress info inside a session variable, e.g. Session["actualfileline"] = actualfileline. You'd access Session["actualfileline"] from your secondary XHR requests.

这篇关于用的UpdatePanel的AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆