I am new to threading in C#. What I want to do is that I am getting some events for screens from API. Now I want to run those events together on my primary and secondary screen. Here is the code snippet.
private void btn_play_Click(object sender, EventArgs e)
{
var path = "C:\\ActiveProjects\\ScreenPlayerClient\\ScreenPlayerClient\\"
"ScreenPlayerClient\\bin\\Debug\\netcoreapp3.1\\Json\\eventsfile.json";
var events = JsonConvert.DeserializeObject<GetEventsResponseModel>(
File.ReadAllText(path));
var screens = Screen.AllScreens;
foreach (var scr in events.Screens)
{
foreach (var computerscreen in screens)
{
if (scr.Title == computerscreen.DeviceName)
{
Thread thr = new Thread(
new ThreadStart(playContent(scr, computerscreen)));
}
}
}
}
private void playContent(ScreenResponseModel scr, Screen screen)
{
var fileDetails = apiOperation.DownLoadFile(
scr.Events.FirstOrDefault().VideoLink).Result;
var filepath = SaveVideo(fileDetails);
PlayerForm player = new PlayerForm();
player.videolink = filepath;
player.Location = screen.WorkingArea.Location;
player.StartPosition = FormStartPosition.Manual;
player.screen = screen;
player.ShowDialog();
}
I am getting error "Method Name Expected" at
Thread thr = new Thread(new ThreadStart(playContent(scr,computerscreen)));
CodePudding user response:
Thread thr = new Thread(() => playContent(src,computerscreen));
thr.Start();
CodePudding user response:
playContent(scr,computerscreen)
this calls a function. new Thread
expects a ThreadStart delegate, or something that can be converted to a delegate, i.e. a lambda or a method name.
Try changing it to
new Thread(() => playContent(scr,computerscreen));
However, I would argue for using Tasks rather than raw threads. There is almost never a good reason for creating a Thread
yourself. I.e.
Task.Run(() => playContent(scr,computerscreen));
However, it looks like playContent
is doing something UI related, and that will simply not work. Or it may create multiple UI threads, and that is rarely a good idea. UI classes can only be accessed from the associated UI thread. So I would reconsider the whole plan of using threads in the first place.