当前位置: 移动技术网 > IT编程>开发语言>.net > 浅析c# 线程同步

浅析c# 线程同步

2020年08月30日  | 移动技术网IT编程  | 我要评论
同步是一种只允许一个线程在特定时间访问某些资源的技术。没有其他线程可以中断,直到所分配的线程或当前访问线程访问数据完成其任务。在多线程程序中,允许线程访问任何资源所需的执行时间。线程共享资源并异步执行

同步是一种只允许一个线程在特定时间访问某些资源的技术。没有其他线程可以中断,直到所分配的线程或当前访问线程访问数据完成其任务。

在多线程程序中,允许线程访问任何资源所需的执行时间。线程共享资源并异步执行。 访问共享资源(数据)是有时可能会暂停系统的关键任务。所以可以通过线程同步来处理它。

主要场景如:存款,取款等交易业务处理。

线程同步的优点

  • 一致性维护
  • 无线程干扰

c#锁定

使用 c# lock关键字同步执行程序。它用于为当前线程锁定,执行任务,然后释放锁定。它确保其他线程在执行完成之前不会中断执行。

下面,创建两个非同步和同步的例子。

c# 示例:非同步

在这个例子中,我们不使用锁。此示例异步执行。换句话说,线程之间存在上下文切换。

using system;
using system.threading;
class printer
{
  public void printtable()
  {
    for (int i = 1; i <= 5; i++)
    {
      thread t = thread.currentthread;
      thread.sleep(200);
      console.writeline(t.name+" "+i);
    }
  }
}
class program
{
  public static void main(string[] args)
  {
    printer p = new printer();
    thread t1 = new thread(new threadstart(p.printtable));
    thread t2 = new thread(new threadstart(p.printtable));
    t1.name = "thread 1 :";
    t2.name = "thread 2 :";
    t1.start();
    t2.start();
  }
}

执行上面示例代码,可以看到以下输出结果 -

thread 2 : 1
thread 1 : 1
thread 2 : 2
thread 1 : 2
thread 2 : 3
thread 1 : 3
thread 2 : 4
thread 1 : 4
thread 2 : 5
thread 1 : 5

c# 线程同步示例

在这个例子中,我们使用lock块,因此示例同步执行。 换句话说,线程之间没有上下文切换。在输出部分,可以看到第二个线程在第一个线程完成任务之后开始执行。

using system;
using system.threading;
class printer
{
  public void printtable()
  {
    lock (this)
    {
      for (int i = 1; i <= 5; i++)
      {
        thread t = thread.currentthread;
        thread.sleep(100);
        console.writeline(t.name + " " + i);
      }
    }
  }
}
class program
{
  public static void main(string[] args)
  {
    printer p = new printer();
    thread t1 = new thread(new threadstart(p.printtable));
    thread t2 = new thread(new threadstart(p.printtable));
    t1.name = "thread 1 :";
    t2.name = "thread 2 :";
    t1.start();
    t2.start();
  }
}

执行上面示例代码,可以看到以下输出结果 -

thread 1 : 1
thread 1 : 2
thread 1 : 3
thread 1 : 4
thread 1 : 5
thread 2 : 1
thread 2 : 2
thread 2 : 3
thread 2 : 4
thread 2 : 5

以上就是浅析c# 线程同步的详细内容,更多关于c# 线程同步的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网