2 回答

TA貢獻1847條經驗 獲得超7個贊
您應該將其分成不同的后臺工作人員。當您的流程到達需要用戶輸入的點時,完成/完成您的后臺工作程序,然后收集 UI 線程上的輸入,然后使用該輸入啟動下一個工作程序。
我建議使用任務/異步/等待方法來代替后臺工作人員。這將使這種過程更容易編寫和理解:
private void async RunTheJob()
{
// Run Part1 async and wait for the result
var result1 = await Part1();
// Now collect your UI input based on result1
var uiInput = ......;
// Run Part2 async and wait for the result
var result2 = await Part2(uiInput);
}
private Task<Part1ReturnObjectTypeHere> Part1()
{
Part1ReturnObjectTypeHere result = null;
...do async work here to populate result...
return result;
}

TA貢獻1828條經驗 獲得超13個贊
你基本上有兩個選擇:
(最佳實踐)正如其他人所指出的,最佳實踐是使用 async/await 鏈來異步完成工作,而不是后臺工作人員。您只需將所有后臺作業代碼放入異步方法中并使用await 關鍵字調用它即可。
下面是一個示例,可用于提示無限數量的提示并隨后繼續作業。
? ? //You can bind this to a Button or any other WPF event,
? ? // the point is that it should be run from UI thread
? ? private async void JobStartEvent()
? ? {
? ? ? ? JobResult jobResult = new JobResult
? ? ? ? {
? ? ? ? ? ? JobStatus = JobStatus.NotStarted
? ? ? ? };
? ? ? ? while (jobResult.JobStatus != JobStatus.Done)
? ? ? ? {
? ? ? ? ? ? jobResult = await DoLongJob(jobResult.ContinuationInfo);
? ? ? ? ? ? if (jobResult.JobStatus == JobStatus.UserPromptRequired)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? jobResult.ContinuationInfo.PromptResult = PromptAndGetResult(jobResult.PromptInfo);
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? private async Task<JobResult> DoLongJob(JobContinuationInfo continuationInfo)
? ? {
? ? ? ? //Do long stuff here
? ? ? ? // continue the job using "continuationInfo"
? ? ? ? //When prompt needed, Do:
? ? ? ? {
? ? ? ? ? ? return new JobResult
? ? ? ? ? ? {
? ? ? ? ? ? ? ? JobStatus = JobStatus.UserPromptRequired,
? ? ? ? ? ? ? ? PromptInfo = new PromptInfo(), //Fill with information required for prompt
? ? ? ? ? ? ? ? ContinuationInfo = new ContinuationInfo() //Fill with information required for continuing the job (can be a delegate to a local function to continue the job)
? ? ? ? ? ? };
? ? ? ? }
? ? ? ? //When done, Do:
? ? ? ? {
? ? ? ? ? ? return new JobResult { JobStatus = JobStatus.Done};
? ? ? ? }
? ? }
? ? private async JobResult DoLongJob()
? ? {
? ? ? ? return JobResult =?
? ? }
? ? private enum JobStatus
? ? {
? ? ? ? NotStarted,
? ? ? ? UserPromptRequired,
? ? ? ? Done
? ? }
? ? internal class JobContinuationInfo
? ? {
? ? ? ? public PromptResult PromptResult { get; set; }
? ? ? ? // Other properties to continue the job
? ? }
? ? private class JobResult
? ? {
? ? ? ? public JobStatus JobStatus { get; set; }
? ? ? ? public PromptInfo PromptInfo { get; set; }
? ? ? ? public JobContinuationInfo ContinuationInfo { get; set; }
? ? }
了解更多: https: //learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
要使用后臺工作程序,您可以使用 Dispatcher.Invoke 方法并將窗口創建代碼傳遞到那里。窗口創建將在 UI 線程中完成,但后臺工作線程將等待它執行,獲取結果(可以是提示的結果),然后繼續執行。
? ? System.Windows.Threading.Dispatcher.Invoke<ResultType>(async () =>
? ? {
? ? ? ? return PromptUserAndGetResult();
? ? });
- 2 回答
- 0 關注
- 176 瀏覽
添加回答
舉報