我使用消费者生产者模型并尝试在中止线程后写入文本框,但它向我显示了一些错误,我理解它不能从线程中完成... 这是我现在的一堆代码:
void LaunchConsumer()
{
while (myReceivedMessage.Count!=8)
{
try
{
var sampleFromCollection = samples32Collection.Take();
TempBuffer.RemoveAt(0);//Remove first object at TempBuffer
TempBuffer.Add(sampleFromCollection);
double TempFreq = (SampleRate *ZeroCrossRate(TempBuffer))/(2*TempBuffer.Count);
//Zero = 387:392
//One = 393:395
int counter = myReceivedMessage.Count;
if(12960.0<TempFreq && TempFreq<13040.0)
{
myReceivedMessage.Add("0");
//MyTextBox.AppendText("0");
TempBuffer.Clear();
TempBuffer = new List<float>(Enumerable.Repeat(0f, (int)(SampleRate * BitTime)));
}
else if(13041.0<TempFreq && TempFreq<13131.0)
{
myReceivedMessage.Add("1");
//MyTextBox.AppendText("1");
TempBuffer.Clear();
TempBuffer = new List<float>(Enumerable.Repeat(0f, (int)(SampleRate*BitTime)));
}
/*else
{
myReceivedMessage.Clear();
}*/
}
catch (InvalidOperationException) { }
}
myWaveIn.StopRecording();
MyTextBox.Text = myReceivedMessage.ToString();//Here I get an error..
Terminate();
}
void Terminate() //Call this to terminate the consumer
{
consumer.Abort();
}
答案 0 :(得分:1)
试试这个:
if (!MyTextBox.Dispatcher.CheckAccess())
{
MyTextBox.Dispatcher.Invoke(() => { MyTextBox.Text = myReceivedMessage.ToString(); });
}
else
{
MyTextBox.Text = myReceivedMessage.ToString();
}