I have an application, when a button is clicked, it starts a task which connects to a specific bluetooth device and then have a continuous stream of data coming in and going out. When the user clicks on the button again, I'd like it to check, if the task I created the first time is running, and if it is, terminate the task. I was thinking of cancelling the task with CancellationToken, but I can't get passed of checking if the task is running or not. Right now, when I click the button the first time, it creates the task and does everything nicely. When I click the button the second time, it still goes past the if statement, thinking the task isn't running and tries to create the task again and connect the bluetooth device again the then gets stuck.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
using System.Threading;
namespace app
{
class Bluetooth
{
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
public BluetoothClient client;
BluetoothDeviceInfo[] devices;
private Task connectionTask;
private void Connect() //This is called from button click
{
if (connectionTask == null ||
connectionTask.IsCompleted == false &&
connectionTask.Status != TaskStatus.Running &&
connectionTask.Status != TaskStatus.WaitingToRun &&
connectionTask.Status != TaskStatus.WaitingForActivation)
{
connectionTask = Task.Factory.StartNew(ConnectionTask);
}
else
{
var form1 = new Form1();
form1.message("Client already connected", 3);
}
}
private void ConnectionTask()
{
//Do Bluetooth connection stuff here which, once connected, will stay in an infinite while loop.
}
}
}
Ive changed the code to the following, but still only get Client connected messagebox. As I understand, because I have Thread.Sleep(100000) the Task should still count as running?
class Bluetooth
{
private Task connectionTask;
public void bluetooth()
{
Connect();
}
private void Connect()
{
if (connectionTask == null ||
connectionTask.IsCompleted == false &&
connectionTask.Status != TaskStatus.Running &&
connectionTask.Status != TaskStatus.WaitingToRun &&
connectionTask.Status != TaskStatus.WaitingForActivation)
{
connectionTask = Task.Factory.StartNew(ConnectionTask);
}
else
{
var form1 = new Form1();
form1.message("Client already connected", 3);
}
}
private void ConnectionTask()
{
var form1 = new Form1();
form1.message("Client connected", 1);
Thread.Sleep(100000);
}
}
}