前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用“using” 的 “Cursor”

使用“using” 的 “Cursor”

作者头像
跟着阿笨一起玩NET
发布2018-09-19 15:52:21
7870
发布2018-09-19 15:52:21
举报
文章被收录于专栏:跟着阿笨一起玩NET

很多时候,我们会写下面的这段代码:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
{
    Cursor cursor = Cursor.Current;
    this.Cursor = Cursors.WaitCursor;

    LongTimeMethod();

    this.Cursor = cursor;
}

private void LongTimeMethod()
{
    for (int i = 0; i < 200; i++)
    {
        label1.Text = i.ToString();
        label1.Refresh();
        System.Threading.Thread.Sleep(10);
    }
}

这段代码在执行LongTimeMethod的时候,设置鼠标的状态为WaitCursor.

可是这段代码是有问题的,比如LongTimeMethod() 方法抛出异常的时候,Cursor 就会始终是WaitCursor.

所以比较安全的做法是:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
 {
     Cursor cursor = Cursor.Current;
     try
     {
         this.Cursor = Cursors.WaitCursor;
         LongTimeMethod();
     }
     finally {
         this.Cursor = cursor;
     }
 }

看到try,finally ,有没有让你想到什么呢?,对了using 可以生成try-finally

代码语言:javascript
复制
public class WaitCursor : IDisposable
{
    private Cursor cursor;

    public WaitCursor()
    {
        this.cursor = Cursor.Current;
        Cursor.Current = Cursors.WaitCursor;
    }

    public void Dispose()
    {
        Cursor.Current = cursor;
    }
}

使用的时候,只需要:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
{
    using(new WaitCursor())
    {
        LongTimeMethod();
    }
}

在using块结束的时候,会自动的调用WaitCursor的Dispose方法,从而设置当前Cursor 为保存的cursor.

如果你仔细的看的话,你会发现Cursor 继承了IDisposable 接口。

image
image

所以有人就说了可以直接:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
{
    using (Cursor.Current = Cursors.WaitCursor)
    {
        LongTimeMethod();
    }
}

如果你第一次运行的话,可以发现的确能正常工作,可是事实上上面的代码是有问题的。

这段代码会调用Cursors.WaitCursor.Dispose() 方法,从而当你第二次调用的时候,你会得到null,因为WaitCursor已经dispose了:

image
image

有一种变通的方法,下面的代码可以正常工作:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
{
    using (Cursor.Current = new Cursor(Cursors.WaitCursor.CopyHandle()))
    {
        LongTimeMethod();
    }
}

本文参考自:http://www.codeproject.com/Articles/6287/WaitCursor-hack-using-using

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013-03-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档