通过显示进度条执行进度 [英] Display progress of execution through progress bar

查看:429
本文介绍了通过显示进度条执行进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个愚蠢的问题,但我坚持。我执行一个存储过程,形成我的代码
过程需要时间,所以为了这个,我正在显示一个进度条,显示执行的进展,但存储过程执行并没有什么,而我递增进度条的值



这是我的代码

 无效btnYes_Click(对象发件人, EventArgs五)
{
如果(DialogResult.Yes == MessageBox.Show(你确定,,MessageBoxButtons.YesNo))
{

{
dbDataEntities DB =新dbDataEntities();
字符串更改为MyQuery =DECLARE @return_value诠释EXEC @return_value = [DBO] [ssspUpdateMarksOfStudent]选择返回值'= @return_value。
//progressbar1.Maximum = 5000;
//progressbar1.value =?; //我怎么能增加它
//
db.Database.ExecuteSqlCommand(更改为MyQuery);



}
赶上(异常前)
{
MessageBox.Show(ex.Message);
}
}
}



此外,我何乐而不为呢通过设置电流值秒表这并没有增加,而过程的执行

 秒表ST =新的秒表(); 
st.Start();
progressbar1.Maximum = 5000;
progressbar1.Value = Convert.ToInt16(st.Elapsed.Seconds);
//我的存储过程调用
st.Stop();



所以它只能通过使用背景工人或有任何其他方式做到这一点?



我是新来的编程所以没有使用背景工人太多,所以我试图找到一种替代方法。



请建议。先谢谢了。


解决方案

一个有趣的想法的SqlConnection InfoMessage 事件,当服务器执行打印命令,它触发。你可以在你的存储过程中的某些部分打印并监听此事件。



<预类=郎-SQL prettyprint-覆盖> - DO什么
打印'10已完成百分比;
- 做的另一件事
打印'20已完成百分比;

打印100已完成百分比;



除此之外,使用@哈姆雷特hakobyan的解决方案。 。只显示一个无限进度条






更新:更新包括一个完整的解决方案



首先,我讨厌充分的答案。它可以防止心灵的找到解决方案的能力。相反,我喜欢轻推人进入正确的路径,这样他们就可以走步行。
,而在这里它是无论如何。使用VS2012的测试,NET4,MSIL W7x64SP1和SQL2012下。



我非常耗时的SP。使用 RAISERROR 而不是打印立即发送消息。

 创建过程usp_LongProcess作为开始

声明@i诠释;
声明@msg VARCHAR(50);
将@i = 0;
,而(@i< 100)开始
WAITFOR DELAY '00:00:02';

将@i = @i + 10;
组@msg =转换(VARCHAR(10),@i)+'完成百分比';
RAISERROR(@msg,1,1)WITH NOWAIT


和我的形式




  • 按钮( CallSpButton

  • 一个进度条(进步

  • 标签( statusLabel )和

  • 后台工作(<> SpCaller )code与 WorkerReportsProgress 设置真正



最后,使呼叫

$ b $代码

和b

 私人无效CallSpButton_Click(对象发件人,EventArgs五)
{
CallSpButton.Enabled = FALSE;
SpCaller.RunWorkerAsync();
}

私人无效SpCaller_DoWork(对象发件人,DoWorkEventArgs E)
{
无功自我=(BackgroundWorker的)寄件人;

变种CB =新SqlConnectionStringBuilder
{
数据源=,
InitialCatalog =沙箱,
IntegratedSecurity = TRUE
} ;

使用(VAR CN =新的SqlConnection(cb.ToString()))
{
cn.FireInfoMessageEventOnUserErrors = TRUE;
cn.Open();
cn.InfoMessage + =(0,参数)=> self.ReportProgress(0,args.Message);

使用(VAR CMD = cn.CreateCommand())
{
cmd.CommandText =usp_LongProcess;
cmd.CommandType = CommandType.StoredProcedure;

cmd.ExecuteNonQuery();
}
}
}

私人无效SpCaller_RunWorkerCompleted(对象发件人,RunWorkerCompletedEventArgs E)
{
CallSpButton.Enabled = TRUE;
}

私人无效SpCaller_ProgressChanged(对象发件人,ProgressChangedEventArgs E)
{
VAR消息= Convert.ToString(e.UserState);
的Debug.WriteLine(消息);
statusLabel.Text =消息;

如果(message.EndsWith(完成百分比))
{
INT个百分点;
如果(int.TryParse(message.Split('')[0],出百分比))
progress.Value =个百分点;
}
}


I have a silly problem but i am stuck. I am executing a stored procedure form my code procedure takes time so for this I am displaying a progress bar, which shows the progress of execution, but stored procedure executes and there is nothing to which I increment the value of progress bar.

This is my code

void btnYes_Click(object sender, EventArgs e)
{
   if (DialogResult.Yes == MessageBox.Show("Are you sure", "", MessageBoxButtons.YesNo))
    {
        try
        {
         dbDataEntities db = new dbDataEntities();
        string myquery = "DECLARE @return_value int EXEC    @return_value = [dbo].[ssspUpdateMarksOfStudent] SELECT 'Return Value' = @return_value";
         //progressbar1.Maximum = 5000; 
         //progressbar1.value = ?; // how could i increment it
         //
         db.Database.ExecuteSqlCommand("myquery");



        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

Also i try to do it with stopwatch by setting the current value which did not increment while execution of procedure

Stopwatch st = new Stopwatch();
st.Start();
progressbar1.Maximum = 5000; 
progressbar1.Value = Convert.ToInt16(st.Elapsed.Seconds);
//My stored procedure call 
st.Stop(); 

so is it can only be done by using background worker or is there any other way to do this?

I am new to programming so did not use background worker much so i am trying to find an alternative.

Please suggest. Thanks in advance.

解决方案

One funny idea SqlConnection provides InfoMessage event which fires when server executes a PRINT command. You can print in some parts of your stored procedure and listen to this event.

-- do something
PRINT '10 PERCENT COMPLETED';
-- do another thing
PRINT '20 PERCENT COMPLETED';
...
PRINT '100 PERCENT COMPLETED';

other than that, use @hamlet-hakobyan 's solution. just show a infinite progress bar.


Update: Updated to include a full solution

First of all, I hate to give full answers. It prevents mind's ability to find a solution. Instead I like to nudge people into correct path, so they can walk the walk. But here it is anyway. Tested using VS2012, NET4, MSIL under W7x64SP1 and SQL2012.

My very time consuming SP. Used RaisError instead of Print to send messages immediately.

Create Procedure usp_LongProcess As Begin

    Declare @i Int;
    Declare @msg VarChar(50);
    Set @i = 0;
    while (@i < 100) Begin
        WaitFor Delay '00:00:02';

        Set @i = @i + 10;
        Set @msg = Convert(VarChar(10), @i) + ' PERCENT COMPLETE';
        RaisError(@msg, 1, 1) With NoWait
    End
End

And my form with

  • a button (CallSpButton)
  • a progress bar (progress)
  • a label (statusLabel) and
  • a background worker (SpCaller) with WorkerReportsProgress set true.

And at last the code that makes the call

private void CallSpButton_Click(object sender, EventArgs e)
{
    CallSpButton.Enabled = false;
    SpCaller.RunWorkerAsync();
}

private void SpCaller_DoWork(object sender, DoWorkEventArgs e)
{
    var self = (BackgroundWorker) sender;

    var cb = new SqlConnectionStringBuilder
    {
        DataSource = ".", 
        InitialCatalog = "Sandbox", 
        IntegratedSecurity = true
    };

    using (var cn = new SqlConnection(cb.ToString()))
    {
        cn.FireInfoMessageEventOnUserErrors = true;
        cn.Open();
        cn.InfoMessage += (o, args) => self.ReportProgress(0, args.Message);

        using (var cmd = cn.CreateCommand())
        {
            cmd.CommandText = "usp_LongProcess";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.ExecuteNonQuery();
        }
    }
}

private void SpCaller_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    CallSpButton.Enabled = true;
}

private void SpCaller_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var message = Convert.ToString(e.UserState);
    Debug.WriteLine(message);
    statusLabel.Text = message;

    if (message.EndsWith(" PERCENT COMPLETE"))
    {
        int percent;
        if (int.TryParse(message.Split(' ')[0], out percent))
            progress.Value = percent;
    }
}

这篇关于通过显示进度条执行进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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