1

我想在 C# 中创建一个线程,它将计算计算机麦克风输入处的声音频率。我不是在问 FFT 算法,而是在问如何启动一个线程,以便我可以在 Thread.hz 更改时修改 A.hz 字段。

将只有 1 个线程。

public class A()
{
    Thread t;
    int hz;  <-- i would like to change this when

    A()
    {
        starts Thread
        onchange t.hz modifies and dispays this.hz
    }        
}

class Thread
{
    int hz; <-- this changes

    void computeFrequency() <-- because of that method
    {
        changesHZField...
    }
}
4

3 回答 3

2

正如所承诺的,这是使用 Rx 的解决方案:

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace rxtest
{
    class FrequencyMeter
    {
        Random rand = new Random();
        public int Hz
        {
            get
            {
                return 60+rand.Next(3);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var obs = Observable.Generate<FrequencyMeter, int>(
                new FrequencyMeter(), //state
                x => !Console.KeyAvailable, // while no key is pressed
                x => x, // no change in the state
                x => x.Hz, // how to get the value
                x => TimeSpan.FromMilliseconds(250), //how often
                Scheduler.Default)
                .DistinctUntilChanged() //show only when changed
                ;

            using (IDisposable handle = obs.Subscribe(x => Console.WriteLine(x)))
            {
                var ticks = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(x=>Console.WriteLine("tick")); //an example only
                Console.WriteLine("Interrupt with a keypress");
                Console.ReadKey();
            }
        }
    }
}

异步传递值:

Interrupt with a keypress
60
61
tick
62
60
tick
61
60
tick
62
61
tick
62
60
tick
于 2012-11-15T18:47:43.440 回答
1

You won't have to do anything special - multiple threads will be able to access your hz field. You'll need to consider synchronization issues (http://msdn.microsoft.com/en-us/library/ms173179.aspx)

When you have multiple threads reading/writing the same variable there are all sorts of problems. The easiest thing is probably to follow the link and copy their locking approach.

于 2012-11-14T15:55:16.997 回答
0
public class A()
{
    Thread t;
    int hz;

    A()
    {
        //starts Thread
    }

    internal void Signal(int hz){
        //modifies and dispays this.hz
    }

}

现在 Thread 类可以在每次设置他的属性时调用方法 Signal。要引用 A 类实例,您可以将其传递给 Thread 类构造函数并将引用存储为私有变量,或者将 A 本身声明为静态;这取决于您的整体架构。

class MyThread : Thread
{
    int _hz;
    A _instance;

    public void MyThread(A inst){
        _instance = inst;
    }

    void computeFrequency()
    {
        //changesHZField...
        _instance.Signal(_hz);
    }
}

最后,您可能需要启用跨线程操作,具体取决于您在 A 类和 MyThread 类中所做的事情

于 2012-11-14T16:07:06.617 回答