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();
}
}
}
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.
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.