Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 两个线程的同步_C#_Multithreading_Synchronization - Fatal编程技术网

C# 两个线程的同步

C# 两个线程的同步,c#,multithreading,synchronization,C#,Multithreading,Synchronization,我有两个c#中的线程。。现在我需要等待一个特定的语句被执行,然后才能在另一个线程中继续执行,这显然是一个同步的情况。 是否有任何代码可以像使用内置方法一样执行此操作 以下是代码示例: public void StartAccept() { try { newSock.BeginAccept(new AsyncCallback(Accepted), newSock); }

我有两个c#中的线程。。现在我需要等待一个特定的语句被执行,然后才能在另一个线程中继续执行,这显然是一个同步的情况。 是否有任何代码可以像使用内置方法一样执行此操作

以下是代码示例:

    public void StartAccept()
    {
            try
            {
                newSock.BeginAccept(new AsyncCallback(Accepted), newSock);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Error in arguments while using begin-accept", "Error", MessageBoxButtons.OK);
            }
            catch (ObjectDisposedException)
            {
                MessageBox.Show("socket closed while using begin-accept", "Error", MessageBoxButtons.OK);
            }
            catch (SocketException)
            {
                MessageBox.Show("Error accessing socket while using begin-accept", "Error", MessageBoxButtons.OK);
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show("Invalid operation while using begin-accept", "Error", MessageBoxButtons.OK);
            }
            catch (Exception)
            {
                MessageBox.Show("Exception occurred while using begin-accept", "Error", MessageBoxButtons.OK);
            }

    }
这将从代码选择的所需主机接收数据:

    private void listBox1_Click(object sender, EventArgs e)
    {



        String data = (String)this.listBox1.SelectedItem;

        ip = Dns.GetHostAddresses(data);

        clientIP = new IPEndPoint(ip[0], 5555);

        newSock.Bind(clientIP);
        newSock.Listen(100);

    }
因此,为了开始接收数据,我需要初始化特定远程主机的套接字,这是在单击列表框中显示的主机之一时完成的。
为此,我需要同步。

Java有一种称为Join的东西。我怀疑在C#中也会有一个预定义的方法。

看一看和。它们是使线程之间的同步成为可能的信号

需要等待完成某项任务的第一个线程将执行myEvent。(),它将阻塞,直到另一个线程调用myEvent。()

假设我们有两个线程,其中一个线程需要进行某种初始化,然后另一个线程才能继续。然后在这两者之间共享一个AutoResetEvent,我们称之为myEvent

// Signal example

using System;
using System.Threading;

class MySync
{
    private readonly AutoResetEvent _myEvent;
    public MySync(AutoResetEvent myEvent)
    {
        _myEvent = myEvent;
    }

    public void ThreadMain(object state)
    {
        Console.WriteLine("Starting thread MySync");
        _myEvent.WaitOne();
        Console.WriteLine("Finishing thread MySync");
    }
}

class Program
{
    static void Main(string[] args)
    {
        AutoResetEvent myEvent = new AutoResetEvent(false);
        MySync mySync = new MySync(myEvent);
        ThreadPool.QueueUserWorkItem(mySync.ThreadMain);
        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        myEvent.Set();
        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        Console.WriteLine("Finishing");
    }
}
不要将其与访问顺序无关紧要的共享资源混淆。例如,如果您有一个共享列表或共享字典,则需要将其包装在互斥体中,以确保它们正确执行

// Mutex example

object mySync = new object();
Dictionary<int, int> myDict = new Dictionary<int, int>();

void threadMainA()
{
    lock(mySync)
    {
        mySync[foo] = bar;
    }
}

void threadMainB()
{
    lock(mySync)
    {
        mySync[bar] = foo;
    }
}
//互斥示例
object mySync=新对象();
Dictionary myDict=新字典();
void threadMainA()
{
锁(mySync)
{
mySync[foo]=bar;
}
}
void threadMainB()
{
锁(mySync)
{
mySync[bar]=foo;
}
}

您可以使用AutoResetEvent

在以下示例中,两个方法被不同的线程调用,DoSomethingB()将在DoSomethingB()启动之前执行并完成:


注意:请记住处理自动回复:)

抱歉,我在问题中遗漏了这一点。+1回答被问到的问题,而不是你想象中的问题。就像我做的那样。好啊因此,对于相同的代码格式,如果我的方法startAccept()必须等待事件listBox1_Click(Object Sender,EventArgs e)执行,那么代码会是什么样子?。。不知何故,我无法理解myEvent对应的是什么。@Awik:如果您将上面的问题编辑为包含一些具体的代码示例,则更容易给出更精确的答案。join将等待线程终止,而不是特定的语句
AutoResetEvent resetEvent = new AutoResetEvent(false);

void ThreadWorkerA()
{
    // perform some work
    DoSomethingA();

    // signal the other thread
    resetEvent.Set();
}

void ThreadWorkerB()
{
    // wait for the signal
    resetEvent.WaitOne();

    // perform the new work
    DoSomethingB();
}