English 中文(简体)
C# 只有一个线索执行
原标题:C# Only One Thread Executes

我有一个多行应用程序。 我只需要一条线来执行我的函数和其他线索来通过它。 我执行我的函数时, 我该怎么做呢?

我的方法有点像:

    public void setOutput(int value)
    {
        try
        {
            GPOs gpos = reader.Config.GPO;
            gpos[1].PortState = GPOs.GPO_PORT_STATE.TRUE;
            gpos[2].PortState = GPOs.GPO_PORT_STATE.TRUE;
            Thread.Sleep(WAIT);
            gpos[1].PortState = GPOs.GPO_PORT_STATE.FALSE;
            gpos[2].PortState = GPOs.GPO_PORT_STATE.FALSE;
        }
        catch (Exception ex)
        {
            logger.Error("An Exception occure while setting GPO to " + value + " " + ex.Message);
        }
    }
最佳回答
问题回答

您可以使用 < a href=" "http://msdn. microsoft.com/query/ dev10.query? appId= Dev10IDEF1 & amp; l= EN- US& k=k% 28SYSTEM.Treadding. MUTEX% 29; k% 28MUTEX%29; k% 28MUTEX% 29; k% 28TargetFramworkMoniker-%22. NETFRAMEWORK, VERSION=V4.% 22% 29; k% 28DevLang- CSHARP%29 & amp;rd= true" rel=" nofolpol " > Mutex

using System;
using System.Threading;

class Test
{
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void MyThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
            Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area
", 
            Thread.CurrentThread.Name);

        // Release the Mutex.
        mut.ReleaseMutex();
    }
}

您可以给您的线串命名, 并在方法中检查名称

那么这个解决方案呢?

private AutoResetEvent are = new AutoResetEvent();

public void setOutput(int value)
{
    // Do not wait (block) == wait 0ms
    if(are.WaitOne(0))
    {
        try
        {
            // Put your code here
        }
        finally
        {
            are.Set()
        }
    }
}

与锁定对象的Monitor 相比,似乎更容易(更安全),但也许不太清楚。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签