温馨提示×

c# wait 如何正确使用

c#
小樊
87
2024-11-26 12:21:22
栏目: 编程语言

在C#中,"wait"关键字通常与线程同步相关,如等待一个任务完成或等待某个条件成立。以下是一些关于如何在C#中正确使用"wait"关键字的示例:

  1. 使用Thread.Wait():
using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Thread thread = new Thread(DoWork);
        thread.Start();

        // 等待线程完成
        thread.Join();
    }

    static void DoWork()
    {
        Console.WriteLine("Thread started.");
        Thread.Sleep(2000); // 模拟耗时操作
        Console.WriteLine("Thread finished.");
    }
}
  1. 使用Task.Wait():
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await Task.Run(DoWork);
    }

    static void DoWork()
    {
        Console.WriteLine("Thread started.");
        Thread.Sleep(2000); // 模拟耗时操作
        Console.WriteLine("Thread finished.");
    }
}
  1. 使用Monitor.Wait():
using System;
using System.Threading;

class Program
{
    private static readonly object lockObject = new object();
    private static int counter = 0;

    static void Main()
    {
        Thread thread1 = new Thread(IncrementCounter);
        Thread thread2 = new Thread(CheckCounter);

        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();
    }

    static void IncrementCounter()
    {
        lock (lockObject)
        {
            counter++;
            Monitor.Pulse(lockObject); // 通知等待的线程
        }
    }

    static void CheckCounter()
    {
        lock (lockObject)
        {
            while (counter == 0)
            {
                Monitor.Wait(lockObject); // 等待计数器变为非零
            }
            Console.WriteLine("Counter is not zero.");
        }
    }
}
  1. 使用ManualResetEvent:
using System;
using System.Threading;

class Program
{
    private static ManualResetEvent resetEvent = new ManualResetEvent(false);

    static void Main()
    {
        Thread thread = new Thread(DoWork);
        thread.Start();

        // 等待线程完成
        resetEvent.WaitOne();
    }

    static void DoWork()
    {
        Console.WriteLine("Thread started.");
        Thread.Sleep(2000); // 模拟耗时操作
        Console.WriteLine("Thread finished.");

        // 通知主线程
        resetEvent.Set();
    }
}

请注意,在使用等待机制时,务必确保正确处理异常,以避免死锁和其他同步问题。

0