This question already has answers here:
How to Cancel a Thread?
(4 answers)
Closed 5 years ago.
I'm improving the performance of a 3d engine i created, introducing LockBits and parallel processing. I have a class for the engine with the following method to update a bitmap with the result:
public void draw() {
clearbmp();
// locking bmp
BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, W, H), ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr FirstPixel = bitmapData.Scan0;
int bytes = Math.Abs(bitmapData.Stride) * H;
bpp = Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
rgbarray = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(FirstPixel, rgbarray, 0, bytes);
int count = 0;
for (int k = 0; k < solidos.Count; k++)
{
if (solidos[k] != null && solidos[k].draw)
{
// separating faces of the solid into different threads
Parallel.ForEach(solidos[k].side, f =>
{
// ... do the operations...
});
}
}
// copy the array to the bitmap and unlock
System.Runtime.InteropServices.Marshal.Copy(rgbarray, 0, FirstPixel, bytes);
bmp.UnlockBits(bitmapData);
The code runs as intended to generate a image, but fails when the main program requires it to update several times in a quick succession, the error occurs in bmp.UnlockBits(bitmapData) with the excepion "Generic error in GDI+"
From what i gathered from my research I suppose this happens because the method runs a second time before it finished the first one, thus trying to unlock data that is already unlocked.
If that is correct then how can i abort the running thread when the new one is created? The last call is always the important one
Before starting a new call, wait for the existing call to complete. You could do that by simply using a lock region. This solves the correctness issue. Maybe it's easier to make each computation run into a Task using Task.Run. The resulting Task object is a handle to that computation and can be used to wait for it to complete.
If you want to speed up finishing an old computation run that is no longer needed, add a cancellation mechanism. Here, you could use a volatile bool cancel = false;. Set it to true to cancel. In your parallel loop (and possibly elsewhere), check that boolean variable periodically and terminate if it is found true. You can also use a CancellationTokenSource.
Related
Good evening guys,
I have issue with multithreading. I'm doing multiple audio samples collection using a parallel.foreach. I want to be able to do the collection simultaneously. I'm doing a sort of a producer consumer pattern. But the producer section, which is the audio samples collection is hanging soft of.
In each of the parallel threads:
A blocking collection is created to collect audio samples
A progress bar is created to monitor mic input
Lastly a Record function for recording/collecting audio input
I created a blocking collection array for each process, and using naudio WaveInEvent for recording from mic.
The challenge i'm facing is that
The program does not resume when I minimize the window
Sometimes the program hangs, other times it takes a while before hanging, but overall, the responsiveness is not good at all (Jerky)
Apart from all these the program is working fine.
What can I do for better performance.
Please check my code below. Thanks
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using NAudio.Wave;
public partial class frmAudioDetector : Form
{
//static BlockingCollection<AudioSamples> realtimeSource;
BlockingCollection<AudioSamples>[] realtimeSource;
static WaveInEvent waveSource;
static readonly int sampleRate = 5512;
private void frmAudioDetector_Load(object sender, EventArgs e)
{
try
{
var tokenSource = new CancellationTokenSource();
TabControl.TabPageCollection pages = tabControl1.TabPages;
//Tabs pages.Count is 8
List<int> integerList = Enumerable.Range(0, pages.Count).ToList();
//Parallel.foreach for simultaneous threads at the same time
Parallel.ForEach<int>(integerList, i =>
{
realtimeSource[i] = new BlockingCollection<AudioSamples>();
var firstProgressBar = (from t in pages[i].Controls.OfType<ProgressBar>()
select t).FirstOrDefault();
var firstEmptyComboBox = (from c in pages[i].Controls.OfType<ComboBox>()
select c).FirstOrDefault();
int deviceNum = firstEmptyComboBox.SelectedIndex;
//create a separate task for each tab for recording
_ = Task.Factory.StartNew(() => RecordMicNAudio(deviceNum, firstProgressBar, i));
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Record audio or store audio samples
void RecordMicNAudio(int deviceNum, ProgressBar progressBar, int t)
{
waveSource = new WaveInEvent();
waveSource.DeviceNumber = deviceNum;
waveSource.WaveFormat = new NAudio.Wave.WaveFormat(rate: sampleRate, bits: 16, channels: 1);
waveSource.DataAvailable += (_, e) =>
{
// using short because 16 bits per sample is used as input wave format
short[] samples = new short[e.BytesRecorded / 2];
Buffer.BlockCopy(e.Buffer, 0, samples, 0, e.BytesRecorded);
// converting to [-1, +1] range
float[] floats = Array.ConvertAll(samples, (sample => (float)sample / short.MaxValue));
//collect realtime audio samples
realtimeSource[t].Add(new AudioSamples(floats, string.Empty, sampleRate));
//Display volume meter in progress bar below
float maxValue = 32767;
int peakValue = 0;
int bytesPerSample = 2;
for (int index = 0; index < e.BytesRecorded; index += bytesPerSample)
{
int value = BitConverter.ToInt16(e.Buffer, index);
peakValue = Math.Max(peakValue, value);
}
var fraction = peakValue / maxValue;
int barCount = 35;
if (progressBar.InvokeRequired)
{
Action action = () => progressBar.Value = (int)(barCount * fraction);
this.BeginInvoke(action);
}
else progressBar.Value = (int)(barCount * fraction);
};
waveSource.RecordingStopped += (_, _) => Debug.WriteLine("Sound Stopped! Cannot capture sound from device...");
waveSource.BufferMilliseconds = 1000;
waveSource.StartRecording();
}
}
To access pages[i].Controls from a non-UI thread (e.g. a threadpool threat that will come from Parallel.ForEach) seems wrong.
The NAudio object already uses event driven programming (you provide a DataAvailable handler and RecordingStopped handler) So there's no need to do that setup work in parallel or in any thread other than the main UI thread.
I would not invoke the volume indicator (progress bar) update directly from the DataAvailable handler. Rather I'd update the control on a Timer tick, and just update a shared variable in the DataAvailable handler. This is event driven programming -- there are no threads or tasks are required that I can see apart from the ones that are already used by the wave source IO threads.
e.g.: Use a variable with a simple lock. Access to this data must be governed with a lock because the DataAvailable handler will be invoked on an IO thread to store the current volume, but the value read on the UI thread by the Timer Tick handler, which you can update at a modest rate, certainly no faster than your screen refresh rate. 4 or 5 times per second is likely frequently enough. Your BufferMilliseconds is already 1000 milliseconds (one second) so you may only be getting sample buffers once per second anyway.
Form-level fields
object sharedAccess = new object();
float sharedVolume;
WaveInEvent DataAvailable handler
lock (sharedAccess) {
sharedVolume= ...;
}
Timer Tick handler
int volume = 0;
lock(sharedAccess) {
volume = sharedVolume;
}
progressBar.Value = /* something based on...*/ volume;
Goals:
do a little work as possible in all event handlers on the UI thread.
do as little work as possible in the IO threads (WaveInEvent.DataAvailable handler).
minimize synchronization between threads when it must occur (try to block the other thread for the least amount of time possible).
With the volume meter out of the way, I'm similarly suspicious about how BlockingCollection coordinates access when calling realtimeSource[t].Add(new AudioSamples(floats, string.Empty, sampleRate)); Who is reading from this collection? There is contention here between the IO thread on which the bytes are arriving and whatever thread may be consuming these samples.
If you are just recording the samples and don't need to use them until recording is complete, then you don't need any kind of special synchronization or blocking collection to accumulate each buffer into a collection. You can just add the buffers into a traditional List - provided you don't access it from any other threads until recording is completed. There may be overhead in managing access to that blocking collection that you don't need to incur.
I get a little nervous when I see all the format conversion you've done:
from incoming buffer to array of shorts
from array of shorts to array of floats
from array of floats to AudioSamples object
from incoming buffer to Int16 during the volume computation (Why not use re-use your array of shorts?)
Seems like you could cut out a buffer copy here by going directly from the incoming format to the array of floats, and perform your volume computation on the array of floats or on a pinned pointer to the original buffer data in unsafe mode.
private void RunEveryTenFrames(Color32[] pixels, int width, int height)
{
var thread = new Thread(() =>
{
Perform super = new HeavyOperation();
if (super != null)
{
Debug.Log("Result: " + super);
ResultHandler.handle(super);
}
});
thread.Start();
}
I'm running this function every 10 frames in Unity. Is this a bad idea. Also, when I try to add thread.Abort() inside the thread, it says thread is not defined and can't use local variable before it's defined error.
Is it a good idea to create a new thread every 10 frames in Unity?
No. 10 frames is too small for repeatedly creating new Thread.
Creating new Thread will cause overhead each time. It's not bad when done once in a while. It is when done every 10 frames. Remember this is not every 10 seconds. It is every 10 frames.
Use ThreadPool. By using ThreadPool with ThreadPool.QueueUserWorkItem, you are re-using Thread that already exist in the System in instead of creating new ones each time.
Your new RunEveryTenFrames function with ThreadPool should look something like this:
private void RunEveryTenFrames(Color32[] pixels, int width, int height)
{
//Prepare parameter to send to the ThreadPool
Data data = new Data();
data.pixels = pixels;
data.width = width;
data.height = height;
ThreadPool.QueueUserWorkItem(new WaitCallback(ExtractFile), data);
}
private void ExtractFile(object a)
{
//Retrive the parameters
Data data = (Data)a;
Perform super = new HeavyOperation();
if (super != null)
{
Debug.Log("Result: " + super);
ResultHandler.handle(super);
}
}
public struct Data
{
public Color32[] pixels;
public int width;
public int height;
}
I you ever need to call into Unity's API or use Unity's API from this Thread, see my other post or how to do that.
I have an application where performance-sensitive drawings occur using a WriteableBitmap. An event is called with CompositionTarget.Rendering to actually update the back buffer of the WriteableBitmap. From the MSDN documentation, that means the event is fired once per frame, right before the control is rendered.
The issue that I am having is that the WriteableBitmap's Lock() function takes an extremely long time, especially at larger bitmap sizes. I have previously read that AddDirtyRegion() has a bug that causes the entire bitmap to invalidate, leading to poor performance. However, that doesn't seem to be the case here. From a good bit of low-level checking, it seems that Lock() opens the bitmap's backbuffer for writing on the render thread, which means every time my event handler is called, it has to thread block until the render thread is ready for it. This leads to a noticeable lag when updating the graphics of the bitmap.
I have already tried adding a timeout to the event handler, using TryLock(), so that it won't block for such a long time and cause the performance degradation. This, however, causes a similar effect in that it appears to lag, because larger numbers of bitmap updates get lumped together.
Here is the relevant code from the event handler to show what exactly I am doing. The UpdatePixels() function was written to avoid using the potentially bugged AddDirtyRect():
void updateBitmap(object sender, EventArgs e)
{
if (!form.ResizingWindow)
{
// Lock and unlock are important... Make sure to keep them outside of the loop for performance reasons.
if (canvasUpdates.Count > 0)
{
//bool locked = scaledDrawingMap.TryLock(bitmapLockDuration);
scaledDrawingMap.Lock();
//if (locked)
//{
unsafe
{
int* pixData = (int*)scaledDrawingMap.BackBuffer;
foreach (Int32Rect i in canvasUpdates)
{
// The graphics object isn't directly shown, so this isn't actually necessary. We do a sort of manual copy from the drawingMap, which acts similarly
// to a back buffer.
Int32Rect temp = GetValidDirtyRegion(i);
UpdatePixels(temp, pixData);
}
scaledDrawingMap.Unlock();
canvasUpdates.Clear();
}
//}
}
}
}
private unsafe void UpdatePixels(Int32Rect temp, int* pixData)
{
//int* pixData = (int*)scaledDrawingMap.BackBuffer;
// Directly copy the backbuffer into a new buffer, to use WritePixels().
var stride = temp.Width * scaledDrawingMap.Format.BitsPerPixel / 8;
int[] relevantPixData = new int[stride * temp.Height];
int srcIdx = 0;
int pWidth = scaledDrawingMap.PixelWidth;
int yLess = temp.Y + temp.Height;
int xLess = temp.X + temp.Width;
for (int y = temp.Y; y < yLess; y++)
{
for (int x = temp.X; x < xLess; x++)
{
relevantPixData[srcIdx++] = pixData[y * pWidth + x];
}
}
scaledDrawingMap.WritePixels(temp, relevantPixData, stride, 0);
}
I can't seem to figure out how to avoid the issue of thread blocking with the WriteableBitmap, and I can't see any obvious faults in the code I have written. Any help or pointers would be much appreciated.
Looks like you are not actually using the BackBuffer to write - only to read.
WritePixels writes to the "front" buffer and does not require a lock.
I don't know if you have some other reason to lock it (other threads doing something), but for the code that's here i don't see why you would need to.
I guess I was wrong about not needing a lock to read from BackBuffer (*pixData) - I thought it was only for writes, but I am positive you do not need to to call Lock for WritePixels.
As far as I can tell, you are doing:
Lock the back buffer
Copy something from it to an array
Call WritePixels using this new array
Unlock the back buffer.
How about switching 3 and 4?
WritePixels may internally cause rendering thread (which has higher priority on the message queue) to get a lock on its behalf which is probably a factor in the delay you are seeing.
A little n00b question I still do not understand reading, many StackOverflow answers.
The colorData variable is a byte array updated 25 times/s by Kinect. There is no UI Component.
I thought WriteableBitmap and WritePixels was called in the same Task's thread. But I still get System.InvalidOperationException. I if create a new WriteableBitmap for each loop there is no error.
How should fix my code to reuse my the WriteableBitmap in an efficient way ?
private async Task DoJob(TimeSpan dueTime, TimeSpan interval, CancellationToken token) {
if (dueTime > TimeSpan.Zero)
await Task.Delay(dueTime, token);
WriteableBitmap bitmap = NewColorBitmap(colorW, colorH);
// Repeat this loop until cancelled.
while (!token.IsCancellationRequested) {
try {
bitmap.WritePixels(
new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight),
colorData, bitmap.PixelWidth * Bgra32BytesPerPixel, 0);
}
catch(Exception ex){
// System.InvalidOperationException:
// The calling thread cannot access this object
// because a different thread owns it.
}
// Wait to repeat again.
if (interval > TimeSpan.Zero)
await Task.Delay(interval, token);
}
}
Because WriteableBitmap is bind to WPF rendering Thread I have to do complex code for inter process communication.
So I no longer use it and instead I use Image from Emgu CV (Open CV) that also have better performances.
Calling the WriteableBitmap.WritePixels method
Check the values of height and width. Perhaps the byte array is simply not big enough!
And The stride is the number of bytes from one row of pixels in memory to the next row of pixels in memory.
I just started messing around with C#/.NET/mono and stuff, and I'm trying to make a simple song player. For this, I am using winmm.dll (did not find an easy cross-platform solution). The problem is this: I need to update a trackbar along with the song playing. I have two functions, Player.GetLength and Player.GetCurrentPosition, which return the time in miliseconds. If I call them "normally", everything is ok. But I need to call them in a timer, like this:
new System.Threading.Timer((state) =>
{
length = Player.GetLength();
pos = Player.GetCurrentPosition();
trackBar1.Value = (pos / length) * 100;
}, null, 0, 100);
This is GetLength, and GetCurrentPosition is similar:
public static int GetLength()
{
StringBuilder s = new StringBuilder(128);
mciSendString("status Song length", s, s.Capacity, IntPtr.Zero);
return int.Parse(s.ToString());
}
The problem: when one of these two functions gets called, the program just stops, without any warning or exception thrown. Note: I am using .NET
So I was wondering if you can explain to me where I got it wrong :)
One thing I'd note is that System.Threading.Timer fires it's callback in it's own thread. Since you are interacting with the UI, you'd either want to use System.Windows.Forms.Timer (as a component on the form) or invoke back to the UI, as follows:
new System.Threading.Timer((state) =>
{
length = Player.GetLength();
pos = Player.GetCurrentPosition();
trackBar1.Invoke(new Action(()=>trackBar1.Value = (pos / length) * 100));
}, null, 0, 100);
Likewise, I am not sure if the Player class supports/tolerates multiple threads, but if not, there is the possibility that the whole callback needs to be invoked to the UI.